I know what guard
does in Swift. I have read the questions about using guard
or if let
. However, is there any difference between guard (condition) else { return }
and if !condition { return }
? They seem to do the same thing.
EDIT: This was not asking about guard let
and if let
. I now know that guard let
is a more useful usage of guard
. I was simply asking about the differences between a simple guard
and if
.
There is a difference if you need to declare a variable in the guard statement, i.e.
guard let foo = bar else { return }
In this case, you can continue to use foo as a non-optional in the rest of the method. You can't do this with a simple if statement.
If you're wondering why that's handy:
if let because = nobody {
if let likes = pyramids {
if let of = doom {
// guard can help you avoid this!
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With