-1
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
    }
user804417
  • 155
  • 2
  • 13
  • 2
    Have a look into this : [Guard vs if-let](http://stackoverflow.com/questions/32256834/swift-2-0-guard-vs-if-let) – Dheeraj D Dec 26 '16 at 04:12
  • http://stackoverflow.com/questions/32256834/swift-2-0-guard-vs-if-let – Kirit Modi Dec 26 '16 at 04:27
  • 2
    Regardless of whether this is a duplicate or not, force-unwrapping `error` in `if let myerror = error!` is simply wrong. The point of optional-binding is to test whether a value is `nil` or not before using it. The `if let` block is going to crash at some point. – par Dec 26 '16 at 04:29
  • Can you suggest me the correct if-let code for this corresponding guard? – user804417 Dec 26 '16 at 05:17
  • `if let data = data { print(data.count) } else if let error = error { print(error) }` – Leo Dabus Dec 26 '16 at 05:37
  • Using guard `guard let data = data, error == nil else { return }` – Leo Dabus Dec 26 '16 at 05:40

1 Answers1

1

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
}
Alexander
  • 59,041
  • 12
  • 98
  • 151