Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does a comma mean inside of a guard clause?

Tags:

syntax

swift

While browsing documentation I came across the following section of code.

    guard let button = sender as? UIBarButtonItem, button === saveButton else 
    {
        os_log("The save button was not pressed, cancelling", log: OSLog.default, type: .debug)
        return
    }

I am relatively knew to Swift and I am confused by the meaning of ...UIBarButtonItem, button.... What is the comma , doing here? Is it acting as a logical and &&? Is this syntax legal for all control structures (e.g. if statements) in swift, or is it just for guard statements?

like image 846
AlanSTACK Avatar asked Oct 17 '25 11:10

AlanSTACK


2 Answers

, is almost the same as &&.

if 1 == 1, 2 == 2 {
    print("dd")
}

if 1 == 1 && 2 == 2 {
    print("dd")
}

Both of the above if statements will print dd.

, can be used wherever && can be used, like while, if and guard.

However, with if let or guard let, as the left hand side does not return a Bool, && can't be used and , must be used.

error: test.playground:4:12: error: optional type 'String?' cannot be used as a boolean; test for '!= nil' instead
if let a = a && 2 == 2 {
           ^
           ( != nil)
like image 168
Papershine Avatar answered Oct 20 '25 01:10

Papershine


it's Kind of if inside if i.e. nested If

let say let button = sender as? UIBarButtonItem

now if sender is type of UIBarButtonItem then it will check condition after , i.e. button === saveButton

button is saveButton or not

else it will return after 1st condition failed

like image 22
Abhishek Thapliyal Avatar answered Oct 20 '25 00:10

Abhishek Thapliyal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!