Reputation: 83
I've been attempting to check if the integer value of a text field is valid in a switch statement to cover more possible cases rather having long if/elseif statements.
switch characterTextFields {
case Int(characterTextFields[1].text!) == nil:
validationErrorModal(text: "Level must be a number!")
}
The code above prompts the following error:
Expression pattern of type 'Bool' cannot match values of type '[UITextField]?'
characterTextFields is an array of text fields. I did research about possibly solutions which involved using let and where keywords, but wasn't able to implement correctly. Any suggestions?
Upvotes: 0
Views: 1538
Reputation: 500
it's best solution for guard if you have value int
guard (shippingID != 0 ) else {
ShowAlerts.displayMessage(message: "Error".localized, body: "Select the Shipping Type".localized, messageError: true)
return
}
Upvotes: 0
Reputation: 9544
It would be better to validate as they type. You should implement a UITextFieldDelegate. And then implement this in your delegate:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//Check for illegal characters
return (string.rangeOfCharacter(from: CharacterSet(charactersIn: "0123456789").inverted) == nil)
}
This prevents any illegal entry from happening in the first place.
Upvotes: 0
Reputation: 130152
You could use switch
for that, but you have to switch over that number, not over the input field:
switch Int(characterTextFields[1].text!) {
case nil:
validationErrorModal(text: "Level must be a number!")
case 0?: // switch over optional value
break
}
Usually it is simpler to handle the optional first, e.g. :
guard let level = Int(characterTextFields[1].text!) else {
validationErrorModal(text: "Level must be a number!")
return
}
and then switch over the non-optional value:
switch level {
case 0:
break
default:
break
}
Upvotes: 1
Reputation: 71852
Here is the way you can achieve it:
switch Int(characterTextFields[1].text!) {
case nil:
validationErrorModal(text: "Level must be a number!")
default:
validationErrorModal(text: "Level is a number!")
}
Upvotes: 0
Reputation: 93191
It's easier if you use guard let
:
guard let level = Int(characterTextFields[1].text!) else {
validationErrorModal(text: "Level must be a number!")
return
}
// Do something with your level
Upvotes: 0