I'm following the book
IOS Programming : The Big Nerd Ranch Guide
And I'm in the part where you create a simple app that converts Fahrenheit to Celsius and the final Challenge is to prevent users from typing alphabetical characters, here is my try.
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
let allowedCharacters = CharacterSet.decimalDigits
let characterSet = CharacterSet(charactersIn: string)
return allowedCharacters.isSuperset(of: characterSet)
let existingTextHasDecimalSeparator = textField.text?.range(of: ".")
let replacementTextHasDecimalSeparator = string.range(of: ".")
if existingTextHasDecimalSeparator != nil,
replacementTextHasDecimalSeparator != nil{
return false
}else{
return true
}
}
It works but I get a warning that says 'Code after return will never be executed' is there a better way to do this to prevent this warning? Thank you in advance!
The warning,
is itself self explanatory,The compiler has done analysis on your code and is telling you that any content below
return allowedCharacters.isSuperset(of: characterSet)
will never be executed.As you said that: It works but I get a warning that says 'Code after return will never be executed' is there a better way to do this to prevent this warning?
Ans: In order to remove this warning just remove the entire code below this statement
return allowedCharacters.isSuperset(of: characterSet)
, the warning will be removed.If you are looking for the better approach i would recommend the below approach, there would be better approach than this but it's not in my knowledge.
BTW,
To implement the functionality i.e. Prevent user from entering text. You can simply change the keyboard type,
As changing keyboard type only works in
iPhone
but not iniPad
it's better to implement the characters allowed intextfield
, intextfield
delegate methodshouldChangeCharactersIn
as below,