加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift学习笔记之guard & defer

发布时间:2020-12-14 06:56:37 所属栏目:百科 来源:网络整理
导读:Swift学习笔记之guard defer 参考文档:http://nshipster.cn/guard-and-defer/ guard guard 是一个新的条件声明,表示如果条件不满足时退出当前 block。任何被声明成 guard 的 optional 绑定在其他函数或 block 中都是可用的,并强制在 else 中用 return 来

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 += 1 }
    return x
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读