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

The trouble with .characterIsMember is that it takes a unichar (a typealias for UInt16).

If you iterate your input using the utf16 view of the string, it will work:

let set = NSCharacterSet.letterCharacterSet()
for chr in input.utf16 {
    if set.characterIsMember(chr) {
        println("\(chr) is a letter")
    }
}

You can also skip the loop and use the contains algorithm if you only want to check for presence/non-presence:

if contains(input.utf16, { set.characterIsMember($0) }) {
    println("contains letters")
}

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.


You should use the Strings built in range functions with NSCharacterSet rather than roll your own solution. This will give you a lot more flexibility too (like case insensitive search if you so desire).

let str = "Hey this is a string"
let characterSet = NSCharacterSet(charactersInString: "aeiou")

if let _ = str.rangeOfCharacterFromSet(characterSet, options: .CaseInsensitiveSearch) {
    println("true")
}
else {
    println("false")
}

Substitute "aeiou" with whatever letters you're looking for.

A less flexible, but fun swift note all the same, is that you can use any of the functions available for Sequences. So you can do this:

contains("abc", "c")

This of course will only work for individual characters, and is not flexible and not recommended.