Swift 关键词系列 ——— where

「这是我参与11月更文挑战的第14天,活动详情查看:2021最后一次更文挑战」。

where在 Swift 中使用来过滤事物,在 Swift 的各个地方,where子句提供了一个约束,并明确指示您要使用的数据或类型。where 可用于 switch - case 语句、do - catch 语句以及 if、while、guard、for-in 的条件以及定义类型约束。而我们需要注意在 Swift 3.0 之后某些地方可以用,代表where

在 if 语句里面使用

在上篇文章我们就看到了在if中使用的语法:

if let path = webUrl, path.hasPrefix("https") {    
   //...
}
复制代码

在 guard 中使用

guard let path = webUrl , path.hasPrefix("https") else {
   //...
}
复制代码

在 for 循环中使用

在使用for循环遍历arrays、ranges等,如果想过滤要循环中的一些条件可以使用for in``where

for value in collection where condition
复制代码

下面求偶数的例子:

var numArray: [Int] = [0,1,2,3,4,5,6,7,8,9]
for val in numArray where (val % 2 == 0) {
   print(val)
}
复制代码

在 while 中使用

var numArray:[Int]? = []
while let arr = numArray, arr.count < 5 {
   numArray?.append(arr.count)
}
复制代码

在 switch-case 中使用

   enum Response {
        case error(Int, String)
        case success
    }

    func test() {
        let httpResponse = Response.success
        switch httpResponse {
        case .error(let code, let status) where code == 401:
            print("HTTP Error: \(code) \(status)")
        case .error:
            print("HTTP Request failed")
        case .success:
            print("HTTP Request was successful")
        }
    }
复制代码

在上面的代码中,我们定义了网络请求返回的简单情况,即.error.success。用来返回的值,Response我们只是想检查网络请求响应是否正常。为此,我们使用.error.success。而我们可以将细分一些错误情况如当401的时候我们就知道接口未授权。可能是未登录,或者登录失效。

在 do-catch 中使用

您可以使用do-catch语句通过运行代码块来处理错误。如果do子句中的代码抛出错误,则将其与catch子句进行匹配以确定其中哪一个可以处理错误。

这是do-catch语句的一般形式:

  do {
    try expression
    statements
  } catch pattern 1 {
    statements
 } catch pattern 2 where condition {
    statements
  } catch pattern 3, pattern 4 where condition {
    statements
  } catch {
     statements
  }
 
复制代码

在下面例子写一个模式catch来指示该子句可以处理哪些错误。这里需要注意顺序很重要。

  do {
        try update(name: "Antoine van der Lee", forUserIdentifier: "AEDKM1323")
    } catch User.ValidationError.emptyName {
        // Called only when the `User.ValidationError.emptyName` error is thrown
    } catch User.ValidationError.nameToShort(let nameLength) where nameLength == 1 {
        // Only when the `nameToShort` error is thrown for an input of 1 character
    } catch is User.ValidationError {
        // All `User.ValidationError` types except for the earlier catch `emptyName` error.
    } catch {
        // All other errors
    }
复制代码

在 类型约束 中使用

类型约束是指定类型参数必须从特定的类继承,或者符合特定的协议或协议组合。例如,Swift 的Dictionary类型限制了可以用作字典键的类型。

在 方法 中使用

func doSomething<T>(_ string: T) where T: ExpressibleByStringLiteral {
   print(string)
}
复制代码

上面的对于当传入的元素符合ExpressibleByStringLiteral协议,可以进行方法的实现。

在 扩展 中使用

extension Array where Element : Numeric {
   ...
}
复制代码

上面的对于数组的扩展是当元素符合Numeric协议 可以进行下面{}里面功能。

extension Array where Element == String {
   ....
}
复制代码

上面的对于数组的扩展是当元素是String类型 可以进行下面{}里面的功能。

上面的代码使用了Element ,它是一种通用占位符,可以称作是数组实际类型的“替代品”,这是一个属于泛型的概念,

高阶函数 中的使用

  • removeAll(where:) 移除所有符合的元素 true
  • contains(where:) 返回的所有符合的元素 true
  • first(where:) 返回的第一个符合的元素 true
  • firstIndex(where:)返回的第一个符合的索引 true
  • last(where:)lastIndex(where:) 这同样适用于它返回最后一个元素、索引

案例:

var numArray: [Int] = [0,1,2,3,4,5,6,7,8,9]
numArray.first (where: { $0 % 2 == 0 } )
numArray.firstIndex(where: {$0 % 2 == 0} )
复制代码

猜你喜欢

转载自juejin.im/post/7032644887740858404
今日推荐