swiftguard-statement

Proper Use of the Swift Guard Keyword?


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.


Solution

  • 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
    }