Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

guard let with logical operators

Tags:

swift

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.

like image 703
Alisher Baigazin Avatar asked Oct 22 '25 08:10

Alisher Baigazin


1 Answers

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 lets 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 }
like image 197
Sweeper Avatar answered Oct 24 '25 20:10

Sweeper