iOS開(kāi)發(fā) -- Swift之邏輯控制(三)

循環(huán)結(jié)構(gòu)

  • 用for-in循環(huán)的時(shí)候,我們有時(shí)并不關(guān)心循環(huán)的位置,所以可以這樣使用:計(jì)算2的10次方
var result = 1
var base = 2
var power = 10
for _ in 1...power {
    result *= base
}
  • 在即將到來(lái)的Swift3.0中,蘋(píng)果會(huì)取消C風(fēng)格的for循環(huán),那么如何寫(xiě)一個(gè)可變步長(zhǎng)的for循環(huán)呢,方法如下:
for i in 10.stride (through: 0, by: -0.2) {
    
    print("\(i)")
    
}
//10.stride (through: 0, by: -0.2),表示從10到0(through),每次遞減0.2。其他改變步長(zhǎng)的邏輯依此類(lèi)推。
  • Swift中do-while循環(huán)變成repeat-while循環(huán),do這個(gè)關(guān)鍵字被錯(cuò)誤處理的一種情況占用了,以后會(huì)介紹到。

選擇結(jié)構(gòu)

Swfit對(duì)switch語(yǔ)句做了一些增強(qiáng)功能,具體如下:

  • 在Swift中,switch語(yǔ)句的每一個(gè)case后面,不用主動(dòng)加上break,執(zhí)行完這個(gè)case之后直接就會(huì)跳轉(zhuǎn)出來(lái)。
let rating = "A"
switch rating {
case "A" :
    print("great")              //只會(huì)打印great
case "B" :
    print("just so-so")
case "C" :
    print("it's bad")
default :
    print("error")
}
  • 我們?cè)谄綍r(shí)經(jīng)常會(huì)用到switch去判斷多個(gè)值,以前我們是這樣寫(xiě)的:
//let rating = "A"
let rating = "a"
switch rating {
case "a" :       //'case' label in a 'switch' should have at least one executable statement
case "A" :
    print("great")
case "B" :
    print("just so-so")
case "C" :
    print("it's bad")
default :
    print("error")
}
  • 這樣寫(xiě)會(huì)報(bào)錯(cuò),我們應(yīng)該用如下方式來(lái)表示:
let rating = "a"
switch rating {
case "a","A" :
    print("great")
case "b","B" :
    print("just so-so")
case "c","C" :
    print("it's bad")
default :
    print("error")
}
  • 在Swift中switch的變量可以不是整型,所有的基礎(chǔ)類(lèi)型都可以,如上面的例子rating是一個(gè)String類(lèi)型。
  • swtich語(yǔ)句需要窮舉所有可能的取值,而在Swift中分號(hào)";"不能代表一個(gè)空語(yǔ)句,當(dāng)需要在switch中表示空語(yǔ)句時(shí),這時(shí)候可以用break或者一對(duì)括號(hào)()來(lái)表示。
let rating = "a"
switch rating {
case "a","A" :
    print("great")
case "b","B" :
    print("just so-so")
case "c","C" :
    print("it's bad")
default :
//    print("error")
    ;               //';'statements are not allowed
}

switch的高級(jí)用法

  • Swift中switch語(yǔ)句不僅可以判斷單值,還可以判斷區(qū)間。
let score = 78
switch score {
case 0 :
    print("You got an egg!")
case 1..<60 :
    print("You failed.")
case 60 :
    print("Just passed")
case 61..<80 :
    print("Just so-so")
case 80..<90 :
    print("Good")
case 90..<100 :
    print("Great!")
case 100 :
    print("Perfect!")
default :
    print("Error score.")
}

  • 用switch對(duì)元組進(jìn)行判斷。
let vector = (0,-1)
switch vector {
case (0,0) :
    print("It's origin!")
case (1,0) :
    print("It an unit vector on the positive x-axis.")
case (-1,0):
    print("It an unit vector on the negative x-axis.")
case (0,1) :
    print("It an unit vector on the positive x-axis.")
case (0,-1):
    print("It an unit vector on the negative x-axis.")
default :
    print("It's just an ordinary vector.")
}
  • 對(duì)元組進(jìn)行switch語(yǔ)句判斷的時(shí)候,可以用下劃線"_"忽略元組中某一維度的值,并且元組中也可以使用區(qū)間。
let point = (1,2)
switch point {
case (0,0) :
    print("It's origin!")
case (_,0) :
    print("It on the x-axis.")
case (0,_) :
    print("It on the y-axis.")
case (-2...2,-2...2) :
    print("It's near the origin.")
default:
    print("(\(point.0),\(point.1)) is just an ordinary point.")
}
  • 在switch也可以使用元組的解包功能。
let point = (0,10)
switch point {
case (0,0) :
    print("It's origin!")
case (let x,0) :
    print("It on the x-axis.")
    print("The x value is \(x)")
case (0,let y) :
    print("It on the y-axis.")
    print("The x value is \(y)")
case (let x,let y) :
    print("It's just an ordinary point.")
    print("The point is (\(x),\(y))")
}
  • switch中的新關(guān)鍵字:fallthrough
let rating = "a"
switch rating {
case "a","A" :
    print("great")
    fallthrough
case "b","B" :
    print("just so-so")
case "c","C" :
    print("it's bad")
default :
    print("error")
}
輸出結(jié)果為:
great
just so-so

注意:fallthrough并不會(huì)判斷下一個(gè)case(或default)是否符合switch的條件,而是直接跳到下一個(gè)case(或default)的邏輯中。這使得:

  1. 我們不能使用fallthrough跳到一個(gè)有邏輯判斷(where)語(yǔ)句的case中
  2. 請(qǐng)不要使用switch和fallthrough組合復(fù)雜的判斷邏輯,來(lái)代替if else。fallthrough應(yīng)該用于從一般到特殊的逐層判定。

控制轉(zhuǎn)移

break continue fallthrough

求x^4 - y^2 = 15xy在300以內(nèi)的一個(gè)正整數(shù)解

  • 我們以往的做法:
//x^4 - y^2 = 15*x*y

var gotAnswer = false
for m in 1...300 {
    for n in 1...300 {
        if m*m*m*m - n*n == 15*m*n {
            print(m,n)
            gotAnswer = true
            break
        }
    }
    if gotAnswer {
        break
    }
}
輸入結(jié)果:4 4
  • 在Swift中我們可以這么做:給最外層的循環(huán)起一個(gè)名字
//x^4 - y^2 = 15*x*y

findAnswer:
for m in 1...300 {
    for n in 1...300 {
        if m*m*m*m - n*n == 15*m*n {
            print(m,n)
            break findAnswer
        }
    }
}
//輸出結(jié)果:4 4
  • 這種方式不僅適用于break,continue也可以

return throw

return 會(huì)在函數(shù)部分作介紹
throw 會(huì)在錯(cuò)誤處理部分作介紹

where關(guān)鍵字

  • 往往用于判斷的擴(kuò)展。
let point = (3,-3)
switch point {
case let (x,y) where x == y :
    print("It's on the line x == y")
case let (x,y) where x == -y :
    print("It's on the line x == -y")
case let (x,y) :
    print("It's just an ordinary point")
}
let age = 19

switch age {
case 10...19 :
    print("You're a teenager")
default :
    print("You're not a teenager")

}

if case 10...19 = age {
    print("You're a teenager")
}

if case 10...19 = age where age >= 18 {
    print("You're a teenager and in a college")
}

let vector = (4,0)
if case (let x,0) = vector where x > 2 && x < 5 {
    print("It's the vector")
}
  • 循環(huán)中也可以使用這種case-where模式
for i in 1...100 {
    if i % 3 == 0 {
        print(i)
    }
}

for case let i in 1...100 where i % 3 == 0 {
    print(i)
}
  • Swift語(yǔ)言中的case-where模式,在特定的情況下,快速判定模式,縮短代碼,增加易讀性。

guard關(guān)鍵字

func buy(money: Int , price: Int ,capacity: Int , volume: Int) {
    if money >= price {
        if  capacity >= volume {
            print("I can buy it")
        }
        else {
            print("Not enough capacity")
        }
    }
    else {
        print("Not enough money")
    }
}

func buy2(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("I can buy it")

}
  • 其功能跟我們常用的if-else基本相同,之所以有g(shù)uard這個(gè)關(guān)鍵字是因?yàn)樘O(píng)果建議我們使用這樣的代碼風(fēng)格,先檢驗(yàn)邊界,然后在處理核心邏輯。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容