I'm trying to check whether a specific string contains letters or not.
So far I've come across NSCharacterSet.letterCharacterSet()
as a set of letters, but I'm having trouble checking whether a character in that set is in the given string. When I use this code, I get an error stating:
'Character' is not convertible to 'unichar'
For the following code:
for chr in input{ if letterSet.characterIsMember(chr){ return "Woah, chill out!" } }
To check if a string contains any letter, use the test() method with the following regular expression /[a-zA-Z]/ . The test method will return true if the string contains at least one letter and false otherwise. Copied!
In Swift, how can I check if a String is alphanumeric, ie, if it contains only one or more alphanumeric characters [a-zA-Z0-9] , excluding letters with diacritics, eg, é.
You can use NSCharacterSet
in the following way :
let letters = NSCharacterSet.letters let phrase = "Test case" let range = phrase.rangeOfCharacter(from: characterSet) // range will be nil if no letters is found if let test = range { println("letters found") } else { println("letters not found") }
Or you can do this too :
func containsOnlyLetters(input: String) -> Bool { for chr in input { if (!(chr >= "a" && chr <= "z") && !(chr >= "A" && chr <= "Z") ) { return false } } return true }
In Swift 2:
func containsOnlyLetters(input: String) -> Bool { for chr in input.characters { if (!(chr >= "a" && chr <= "z") && !(chr >= "A" && chr <= "Z") ) { return false } } return true }
It's up to you, choose a way. I hope this help you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With