swiftguard-statement

How does swift guard determine true or false when using = operator


Learning swift 3.1 by reading Language Guide (developer.apple.com). I learned that in swift the assignment operator (=) does not return a value. In control flow chapter got an example of guard statement:

func greet(person: [String: String]) {
    guard let name = person["name"] else {
        return
    }

    print("Hello \(name)!")

    guard let location = person["location"] else {
        print("I hope the weather is nice near you.")
        return
    }

    print("I hope the weather is nice in \(location).")
}

My question is if '=' operator does not return value then:

guard let name = person["name"] else {
    return
}  

How does guard determine name = person["name"] is true or false and depending on that go to else and return?


Solution

  • The purpose of guard is to assert that a value is non-nil, and to guarantee exit of the current scope if it is. This allows the value to be used throughout the rest of your function and to allow your "golden path" to not be nested within several if-statements.

    You can do something similar with an if-let syntax, but it provides no guarantees that the scope must be exited or provide that protected value outside of it's own scope.

    guard let name = person["name"] else {
        return
    }
    // name available here!
    

    vs

    if let name = person["name"] {
        // name available here
    } else {
        // name not available here
    }
    
    // name not available here either
    

    All of this is based on whether the if/guard statements can guarantee the existence of a value, not on truthiness.