天天看点

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
}