If we want to avoid nesting our code with multiple if
statements, we can use guard
instead. guard
will check a condition in the same way, but stoping the code when the condition is not met.
var shoppingList: [String] = [
"Potato",
"Tomato",
"Chicken",
"Salmon"
]
func removeAt(index: Int) {
guard index < shoppingList.count else {
return
}
shoppingList.remove(at: index)
}
guard let
if let
can be also replaced with this new statement.
func sayMyName(name: String?) {
guard let unwrappedName = name else {
return
}
print(unwrappedName)
}
You can shorten this using the same name for the unwrapped value:
guard let name else {
return
}
You can use other keywords instead of return
, like throw
.
guard let name else {
throw NSError()
}
Be the first to comment