Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a string contains letters in Swift? [duplicate]

Tags:

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!"     } } 
like image 604
qmlowery Avatar asked Apr 08 '15 16:04

qmlowery


People also ask

How do I check if a string contains letters?

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!

How do you check if a string is alphanumeric in Swift?

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, é.


1 Answers

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.

like image 105
Victor Sigler Avatar answered Sep 24 '22 08:09

Victor Sigler