警卫vs if-let

时间:2016-12-26 04:03:29

标签: ios swift3 guard

let task = urlSession.dataTaskWithRequest(urlRequest)
    { (data, response, error) -> Void in
    guard error == nil else {
      print("Error while fetching remote rooms: \(error)")
      return
    }

以下区块可以替代上述区块吗?

let task = urlSession.dataTaskWithRequest(urlRequest)
    { (data, response, error) -> Void in
    if let myerror = error! {
      print("Error while fetching remote rooms: \(myerror)")
      return
    }

1 个答案:

答案 0 :(得分:1)

不,这将是正确的“警卫让”替代方案。

let task = urlSession.dataTaskWithRequest(urlRequest) { (data, response, error) -> Void in
    guard error == nil else {
        print("Error while fetching remote rooms: \(error)")
        return
    }

    // guard passed, thus there is no error
}