天天看點

Swift-guard & deferSwift-guard & defer

Swift-guard & defer

參考文檔:http://nshipster.cn/guard-and-defer/

guard

  • guard 是一個新的條件聲明,表示如果條件不滿足時退出目前 block。任何被聲明成 guard 的 optional 綁定在其他函數或 block 中都是可用的,并強制在 else 中用 return 來退出函數、continue 或 break 退出循環,或者用一個類似 fatalError() 的 @noreturn 函數來退出,以離開目前的上下文:
for imageName in imageNamesList {
    guard let image = UIImage(named: imageName) 
        else { continue }
    // do something with image
}
           

defer(推遲)

  • defer的block,總是在目前方法執行後才會執行,一般會在block裡面寫釋放資源代碼。
  • 它會颠倒程式執行順序,應該慎用!避免造成混淆和晦澀,減小代碼的可讀性!
postfix func ++(inout x: Int) -> Int {
    defer { x +=  }
    return x
}