Guard

我們常遇到的一種情況,if else 一大串,一層又一層,看到眼花暸亂,搞得根本不知道現在是跑到哪一層去了,在 Swift 裡有比 if else 更好的寫法,那就是 Guard

使用 Guard 來判斷 error == nil

傳統 Objective-C 寫法

if (error == nil) {
    // doSomething
} else {
    // throw error
}

改用 guard

guard (error == nil) else {
    // throw error
    return // guard 裡面一定要有 return
}

// doSomething

改成用 guard 的好處是判斷式不會一層一層一直增加下去,程式也較美觀易讀,但要注意的是別把邏輯給搞錯了,要想感 guard 後面的判斷式成立之後才去 doSomething 喔,這點有時候連我都會搞糊塗了

使用 Guard 來判斷型態

有時候也可以先判斷 Optional 的物件之後再處理,避免 Optional 裡面是 nil 或是型態不同造成程式的錯誤

// 宣告函式
func doSomething(input:Bool, handler:(obj:AnyObject?) ->Void) ->Void {
    let someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]

    if input {
        handler(obj: someDict)
    } else {
        handler(obj: [1,2,3])
    }
}

// 執行函式
doSomething(true) { (obj) -> Void in
    // 判斷是否為[Int:String] 的型態(Dictionary)
    guard let someDict = obj as? [Int:String] else {
        print("obj not match dictionary")
        return
    }
    // 將 Dictionary 裡面每個 value 印出來
    for (key, value) in someDict {
        print("Dictionary key \(key) -  Dictionary value \(value)")
    }
    // 自行輸入 key 但會印出 Optional
    print( "Value of key = 1 is \(someDict[1])" )
    print( "Value of key = 2 is \(someDict[2])" )
    print( "Value of key = 3 is \(someDict[3])" )
}

results matching ""

    No results matching ""