I am trying to convert some code from Swift 1.2 to 2.0. I have the below code in Swift 1.2
//enable OR disable keys.
if(discountAmountTextField.text.isEmpty){
keypadView.disableNotRequiredKeys()
}else{
keypadView.enableRequiredKeys()
}
There are two ways I can go about converting this to Swift 2.0 guard
and if let
Here's how the code looks like with if let
//enable OR disable keys.
if let text = discountAmountTextField.text {
if text.isEmpty {
keypadView.disableNotRequiredKeys()
} else {
keypadView.enableRequiredKeys()
}
} else {
keypadView.enableRequiredKeys()
}
Here's how it looks using the guard syntax
//enable OR disable keys.
guard let text = discountAmountTextField.text else {
keypadView.enableRequiredKeys()
return;
}
if text.isEmpty {
keypadView.disableNotRequiredKeys()
} else {
keypadView.enableRequiredKeys()
}
I want to know what is considered as a more cleaner and appropriate way of writing. The guard looks cleaner to me but is there a rule of when I should be using one over the other? Is there any way to further simplify the method?
I'd use a where
here:
if let text = discountAmountTextField.text where text.isEmpty {
keypadView.disableNotRequiredKeys()
} else {
keypadView.enableRequiredKeys()
}
It combines two of your failure cases into one.