swift 中的 where

使用场景

  • switch 语句使用 where 配合 if let 限定某些条件。
    let names = ["张三", "李四", "吴奇隆", "周六", "赵七", "吴青峰", "吴镇宇"]
    names.forEach {
        switch $0 {
        case let name where name.hasPrefix("吴"):
            print("\(name)是吴家大院的人")
        default:
            print("hello,\($0)")
        }
    }
  • 配合 for 循环来添加限定条件使代码更加易读。
    let names = ["张三", "李四", "吴奇隆", "周六", "赵七", "吴青峰", "吴镇宇"]
    for name in names where name == "吴奇隆" {
        print("\(name)大哥")
    }
  • 接口扩展使用 where 进行限定(如果希望接口扩展的默认实现只在某些限定的条件下才适用)。例如这些系统的接口扩展:
extension ContiguousArray where Element : BidirectionalCollection {
    public func joined() -> FlattenBidirectionalCollection<ContiguousArray<Element>>
}

extension ContiguousArray where Element : Sequence {
    public func joined<Separator>(separator: Separator) -> JoinedSequence<ContiguousArray<Element>> where Separator : Sequence, Separator.Element == Element.Element
}

这样如果一个 Array 中的元素是不可比较的那么 sort 方法也就不适用了。

    var sortArr: [Int] = [99, 77, 12, 4, 23, 59, 8]
    var unsortArr: [Any] = ["hello", 5, ["name":"Jack"]]
    
    sortArr = sortArr.sorted()
    unsortArr = unsortArr.sorted() //会提示报错
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,026评论 19 139
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,262评论 4 61
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,785评论 18 399
  • 属性 1.例子如下 但是 如果是这样 为什么会报错呢?因为rangeOfThreeItems被声明成常量,即使fi...
    爱偷懒的万万阅读 513评论 0 1
  • 雕塑自己的过程,必定伴随着疼痛与辛苦,可那一锤一凿的自我敲打,终究能让我们收获一个更好的自己。 ——题记 一直以来...
    樱_子阅读 839评论 4 2