Reputation: 1800
Instead to write a big "if" statement, I want to know if this syntax is ok ? I just use the word return if the condition is not respected.
@IBAction func SignUpAction(sender: AnyObject) {
if passwordField1.text != passwordField2.text {
// password dont match
// Pop error
return
}
let user = PFUser()
user.username = emailField.text
user.password = passwordField1.text
user.signUpInBackgroundWithBlock { (suceeded: Bool, error: NSError?) -> Void in
if error == nil {
// Log the user
}else{
// Display an error
}
}
}
Or I need to write it like this :
@IBAction func SignUpAction(sender: AnyObject) {
if passwordField1.text == passwordField2.text {
let user = PFUser()
user.username = emailField.text
user.password = passwordField1.text
user.signUpInBackgroundWithBlock { (suceeded: Bool, error: NSError?) -> Void in
if error == nil {
// Log the user
}else{
// Display an error
}
}
}else{
// Error : password dont match
// Pop error
}
}
the first syntax is more clear if need to try many conditions but I'm not sure it's good to write the code like that. Thanks
SOLUTION : (with matt answer and Apple Doc on "guard" : The first statement need to be write like this :
guard passwordField1.text == passwordField2.text else {
print("pop error")
return
}
Upvotes: 1
Views: 593
Reputation: 535989
Actually, I'd use the first syntax, expressed as a guard
statement:
guard passwordField1.text == passwordField2.text else { return }
This is exactly what guard
is for: if conditions are not met, go no further. A succession of multiple guard
statements (because multiple conditions must be met) is quite standard.
Upvotes: 3