swiftnscharacterset

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


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!"
    }
}

Solution

  • You can use NSCharacterSet in the following way :

    let letters = NSCharacterSet.letters
    
    let phrase = "Test case"
    let range = phrase.rangeOfCharacter(from: letters)
    
    // 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.