John John - 10 days ago 8
Swift Question

Guard statements in Swift?

Question 1: Guard statement return value is a

new variable
when the condition true or
new variable
with the value of nil when the condition is false ?

Question 2: Will program stop when the first guard statement is false ?
For example : assume that first guard statement below eveulates false , the second and others will continue to execute or never execute?

func submit() {
guard let name = nameField.text else {
show("No name to submit")
return
}

guard let address = addressField.text else {
show("No address to submit")
return
}

guard let phone = phoneField.text else {
show("No phone to submit")
return
}

sendToServer(name, address: address, phone: phone)
}

func sendToServer(name: String, address: String, phone: String) {
...
}

Answer

Question 1: Answer

guard gives you an unwrapped value and can only be used with optionals. So, it may return a value or a nil. If its a nil/If condition is false, then the else block is executed of the corresponding guard statement

Question 2: Answer

If the first statement tends to be false, then it will go to else block and will return out of the function. No other body of the function will be executed.

Just to add something:
If you want to execute something after the end of the function, irrespective of the guard if it returns in mid way, then you can use defer.

func submit() {

   //It acts like a finally block in JAVA or C#
   defer {print("Will be executed irrespective of true or false by guard at the end of the function.")}

    guard let name = nameField.text else {
        show("No name to submit")
        return
    }

    guard let address = addressField.text else {
        show("No address to submit")
        return
    }

    guard let phone = phoneField.text else {
        show("No phone to submit")
        return
    }

    sendToServer(name, address: address, phone: phone)
}