Reputation: 1276
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?
Upvotes: 1
Views: 7963
Reputation: 106
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.
Upvotes: 5
Reputation: 63271
As @Hasmish pointed out, let name = person["name"]
is a optional-binding-condition
. It evaluates to true when the right side is not nil
, and has a side effect of binding the wrapped value to the identifier on the left side.
The optional-binding-condition
has no regard to whether the right hand side is true
/false
.
let optionalBool: Bool? = false
guard let bool = optionalBool else {
fatalError("This will never be called, because `optionalBool` is not `nil`")
}
In fact, the right hand side doesn't even have to be a Bool
, as you demonstrated.
Upvotes: 1