Ans :
Basic Difference :
Guard let
Early exist process from the scope
Require score existing like return, Throw etc.
Create a new variable those can be access out the scope.
if let
Can not access out the scope.
no need to return statement. But we can write
Note : Both are used to unwrapped the Optional variable.
Guard let
guard condition else { //Generally return }
If let
Q. return is mandatory in guard let statement ?
A. Exit is mandatory in guard let statement. So return or throw is mandatory in guard let. Otherwise it gives compile time error.
Basic Difference :
Guard let
Early exist process from the scope
Require score existing like return, Throw etc.
Create a new variable those can be access out the scope.
if let
Can not access out the scope.
no need to return statement. But we can write
Note : Both are used to unwrapped the Optional variable.
Guard let
- A guard statement is used to transfer program control out of a scope if one or more conditions aren’t met.
- The value of any condition in a guard statement must be of type Bool or a type bridged to Bool. The condition can also be an optional binding declaration.
guard condition else { //Generally return }
func submit() {
guard let name = nameField.text else {
show("No name to submit")
return
}
If let
- Also popular as optional binding
- For accessing optional object we use if let
if let roomCount = optionalValue {
print("roomCount available")
} else {
print("roomCount is nil")
}
Q. return is mandatory in guard let statement ?
A. Exit is mandatory in guard let statement. So return or throw is mandatory in guard let. Otherwise it gives compile time error.
Very helpful thankyou
ReplyDelete