I just joined the forum but came up independently with a similar solution, which however causes problems. In the playground I wrote this and it works:
func tellDigits() -> Bool {
let characterSet = NSCharacterSet.letters
let phrase = “678”
let stringOfCharacters = phrase.rangeOfCharacter(from: characterSet) // gives nil without error although it is not optional
// range will be nil if no letters is found
if stringOfCharacters == nil {
return true
} else {
return false
}
}
tellDigits() // gives true as it should
However, if I incorporate that into the application, I get errors.
let characterSet = NSCharacterSet.letters
let stringOfCharacters = textField.text.rangeOfCharacter(from: characterSet)
if stringOfCharacters != nil {
return false
} else {
return true
} // error: value of optional type string not unwrapped.
if stringOfCharacters != nil {
return false
} else {
return true
}
if instead I write
let stringOfCharacters = string.rangeOfCharacter(from: characterSet)
I get an attention mark that this will never be executed, most probably because of the same reason. Also we want the text in the textfield to be prevented from having letters first. So I don’t understand, how to unwrap “stringOfCharacters”. I tried everything but without success. There must be a different solution.