##邏輯分支編程
一. 分支的介紹swift
二. if分支語句設計
具體實例(代碼爲例)code
let a = 10 // 錯誤寫法: //if a { // print("a") //} // 正確寫法 if a > 1 { print(a) } let score = 87 if score < 60 { print("不及格") } else if score <= 70 { print("及格") } else if score <= 80 { print("良好") } else if score <= 90 { print("優秀") } else { print("完美") }
三. 目運算符字符串
四. guard的使用it
guard是Swift2.0新增的語法io
它與if語句很是相似,它設計的目的是提升程序的可讀性數據類型
guard語句必須帶有else語句,它的語法以下: 當條件表達式爲true時候跳過else語句中的內容,執行語句組內容 條件表達式爲false時候執行else語句中的內容,跳轉語句通常是return、break、continue和throw語法
通常形式程序
guard 條件表達式 else { // 條換語句 break } 語句組
代碼具體實例
//三目運算符 let age = 20 let result = age > 10 ? "大於它" : "小於它" print(result) //guard //OC 寫法 //func result(age : int) -> Bool { // if age >= 18 { // print("大於它") // return true // } // else{ // print("小於它") // return true // } //} //Swift 寫法 func result(age : Int) -> Bool { guard age >= 18 else { print("小於它") return false } print("大於它") return true } result(30)
五. switch分支
switch的介紹
Switch做爲選擇結構中必不可少的語句也被加入到了Swift中
只要有過編程經驗的人對Switch語句都不會感到陌生
但蘋果對Switch進行了大大的加強,使其擁有其餘語言中沒有的特性
switch的簡單使用
基本用法和OC用法一致 -不一樣之處: switch後能夠不跟() case後能夠不跟break(默認會有break)
具體實例 (代碼):
let sex = 0 switch sex { case 0 : print("男") case 1 : print("女") default : print("其餘") }
let sex = 0 switch sex { case 0: fallthrough case 1: print("正常人") default: print("其餘") }
let m = 5 let n = 10 var result = 0 let opration = "+" switch opration { case "+": result = m + n case "-": result = m - n case "*": result = m * n case "/": result = m / n default: result = 0 } print(result)
let score = 88 switch score { case 0..<60: print("不及格") case 60..<80: print("幾個") case 80..<90: print("良好") case 90..<100: print("優秀") default: print("滿分") }