How can I use guard let like:
guard let value = vm.value1 || let value = vm.value2 else { return }
I need to check value1, If it has value, continue to work with it, else check value2, and work with it, else: quit. Only one can have value.
CodePudding user response:
The semantics you are describing seems to be:
guard let value = vm.value1 ?? vm.value2 else { return }
If vm.value1
is not nil, value
would be bound to its value, and the code after the guard
statement would be executed.
Otherwise, if vm.value2
is not nil, value
would be bound to its value, and the code after the guard
statement would be executed.
Otherwise, return
would be executed.
Similarly, multiple let
s could be used to achieve something similar to the semantics of the logical "AND":
guard let value1 = vm.value1, let value2 = vm.value2 else { return }
The code after the guard
statement is only executed if vm.value1
is not nil, and vm.value2
is not nil, and value1
and value2
are bound to the corresponding values.
Also note that you can mix arbitrary boolean conditions with the let
bindings too:
guard let value = vm.value1, someBool || someOtherBool else { return }
CodePudding user response:
You can't use logical operator with guard statement But there is another way of performing AND operator
guard let value = vm.value1,
let value = vm.value2 else {
return
}
And OR operator functionality can be achieve by using ternary operator with guard statement
guard let value = ((vm.value1 != nil) ? vm.value1 : vm.value2 else {
return
}
And you can use the value after else statement