if true {
print("This statement gets executed when condition is true")
}
vs.
guard true else {
print("This statement gets executed when condition is true")
}
☝🏾 the if
and guard
statements are effectlively the same let's see how they are different...
if let value = someOptional {
// ...
}
print("\(value)") // Error - `value` is only in scope inside the `if` block
vs.
guard let value = someOptional else {
// ...
return
}
print("\(value)") // Works - guard clause ensures `value` exists
Guard statements give you a cleaner way to unwrap optionals than If statements since they're kept in scope when the guard condition evaluates to true..