0

I've been looking up how to use the guard keyword in Swift. Recently a developer told me that the code below will print "success" if there's no error in the closure.

for attachment in attachments! {
    attachment.fetchData { (data, error) in 
        guard let error = error else {
            print(“success”)
            return
        }

        print(error.localizedDescription)
}

I'm a bit confused by his statement. After reading the closure and guard keyword documentation from Apple, it looks to me like his code will print out "success" only when there is an error.

I feel like he's using it in reverse, but I may be wrong. Can someone break it down for me and explain if success is printed when there is or is not an error?

Thank you.

Hamish
  • 78,605
  • 19
  • 187
  • 280
  • Success is printed when there is no error. The guard statement is entered when the guard condition is false (or the variable is nil in the case of a `guard let`). – dan Mar 02 '17 at 16:59
  • @dan - Ah, I see, so if error is not equal to error, or there is no error (error is nil), then it reads success. Thank you. I thought the guard condition would be entered if the statement were true, like an if statement. Would you like to submit an answer for me to accept? – BlueishVelvet Mar 02 '17 at 17:03
  • You really shouldn't use a `guard` to encapsulate the logic for a happy execution path – use it only for failure logic. In this case you could use an `if let` instead, and do your error printing and returning there. Or use a `guard let` on the `data` rather than the `error`. – Hamish Mar 02 '17 at 17:04
  • guard condition else { statements } if condition is true the variable ;in your case it error will be used statements after that in the method, else it will print success and return from the method. – Deepak Singh Mar 02 '17 at 17:04
  • @LeoDabus - I thought the same thing as vadian, could you explain what you meant about it being "misleading", please? – BlueishVelvet Mar 02 '17 at 17:06
  • You should use `guard let data = data, error == nil else { print(error) return ` ... as also stated by Hamish **happy path** – Leo Dabus Mar 02 '17 at 17:07
  • Thanks @LeoDabus, That makes much more sense. if you'd like to summarize in an answer, I can go ahead and accept it. – BlueishVelvet Mar 02 '17 at 17:09

1 Answers1

0

The use of guard to unwrap the error is very misleading. You should use it to unwrap your data and make sure there is no error and provide an early exit to your method in case of error.

Just change your guard statement to:

guard let data = data, error == nil else { 
    print(error ?? "") 
    return
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571