SWIFT邏輯控制之where
這裏對where的應用舉個例子:
for i in 0...100{
if i%3 == 0{
print(i)
}
}
//上面的代碼通過where實現:
for i in 0...100 where i%3 == 0{
print(i)
}
在swift3中,使用if case這樣的模式匹配,where關鍵字可以省略,轉而使用,(逗號)代替即可
let age = 19
if case 10...19 = age , age >= 18{
print("You're a teenager and in a college!")
}
一次循環一個大括號就完成了,增加了代碼的易讀性。
SWIFT邏輯控制之guard:確保一個條件爲真true
guard 絕對有存在的必要,尤其是當守護的是一個可選類型的時候。
必須包含else不然guard也沒有存在的必要了
平常的書寫方式
func buy( money: Int , price: Int , capacity: Int , volume: Int){
if money >= price{
if capacity >= volume{
print("I can buy it!")
print("\(money-price) Yuan left.")
print("\(capacity-volume) cubic meters left")
}
else{
print("No enough capacity")
}
}
else{
print("Not enough money")
}
}
使用guard後:
func buy( money: Int , price: Int , capacity: Int , volume: Int){
guard money >= price else{
print("Not enough money")
return
}
guard capacity >= volume else{
print("Not enough capacity")
return
}
print("\(money-price) Yuan left.")
print("\(capacity-volume) cubic meters left")
}
本文作爲學習筆記,記錄與總結swift學習的過程