swift 中的 where

376 阅读1分钟

使用场景

  • 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() //会提示报错