//忘卻OC下的,YES、NO 吧 這里只有true 赢乓、false
eg.:
let yes: Bool = true
let no: Bool = false
布爾判斷
let isEqual = (1 == 2)// == 等等判斷
let isNotEqual = (1 != 2) // != 不等判斷
let reverseEqual = !(1 == 2) // ! 反轉(zhuǎn)判斷
let isGreater = (1 > 2)
let isLess = (1 < 2)
<=谤饭、 >= ...
邏輯判斷
let and = true && true //邏輯與
let or = true || false //邏輯或
if 分支判斷
//跟其他語言沒有什么不一致
if (condition) {
print("true")
}else if(othercondition){
print("...")
}
//在大量羅列各種判斷條件時,注意條件組合判斷炫欺,可以簡化代碼乎完。
三目運(yùn)算符
(<condition>) ? <True value> : <False value>
While 循環(huán)
while <condition> {
<loop code>
//可以打斷循環(huán),關(guān)鍵字 break
}
repeat-while 循環(huán)
//等同于 熟悉的 do - while
repeat{
<loop code>
}while <condition>
區(qū)間
//閉區(qū)間
let closedRange = 0...5
//半開區(qū)間
let halfOpenRange = 0..<5
//這是不是很像數(shù)學(xué)上的概念了竣稽,親切4雅隆;舻!
For 循環(huán)
for <constant> in <countable range> {
<loop code>
}
eg.:
let count = 10
var sum = 0
for i in 1..count {
sum += i
}
eg.:
for _ in 0..<count {
//循環(huán)固定次數(shù)娃弓,忽略了循環(huán)因子典格。
}
eg.:
//結(jié)合where 進(jìn)行條件約束
sum = 0
for i in 1...count where i % 2 == 1 {
sum += i
}
labeled statements
//如果你了解 goto 這個關(guān)鍵字的話,應(yīng)該會了解要說什么了~ 是一樣一樣的
var sum = 0
rowLoop: for row in 0..<8 {
columnLoop: for column in 0..<8 {
if row == column {
continue rowLoop
}
sum += row * column
}
}
上面rowLoop台丛、columnLoop 就是標(biāo)簽耍缴,標(biāo)明的應(yīng)該是一個代碼塊{}的入口。適當(dāng)用用還可以哦~
Switch 分支
//直接上例子
let number = 10
switch number {
case 0:
print("zero")
//多條件分支組合
case 1, 2:
print("> 0")
//應(yīng)用區(qū)間
case 4...10:
print("close rage")
//應(yīng)用where條件綁定
case let x where x == 12:
print("x")
//匹配其它條件 這里寫到最后挽霉,等同于default:
/*
case _ :
print("...")
*/
default:
print("non-zero")
}
//元組匹配
let detail = (age: 18, height: 170 , weight: 60)
switch detail {
case (18, _,_):
print("only concern age")
case (_, height: 170, _):
print("only concern height")
case (_, let height , 60):
print("only concern weight, height = \(height)")
default:
print("the other one")
}