Guard vs if-let

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

Is the below block can be alternative of the above one?

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

There are 1 answers

0
Alexander On

No, this would be the correct "guard let" alternative.

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
}