Guard statement work as an error handler. If we have to send values to server which can be empty or may not be in that condition we can use guard so that if the value is nil then app will not get crashed.
let's see how to use Guard Statement in Swift.
example:
func submittingToServer() {
guard let name = nameField.text else {
show("No name to submit") // if not unwrapped this line will display
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
}
valuesSendToServer(name, address: address, phone: phone)
}
func valuesSendToServer(name: String, address: String, phone: String) {
...// sending non optional values
}
As we can see we are sending non optional strings to the server so server may or may not get nil values, to avoid this situation we use guard. It will unwrap the values and if unwrapping fails you will get some text which is written in else statement.
0 Comment(s)