Swift Language Check if String contains Characters from a Defined Set


Example

Letters

3.0
let letters = CharacterSet.letters

let phrase = "Test case"
let range = phrase.rangeOfCharacter(from: letters)

// range will be nil if no letters is found
if let test = range {
   print("letters found")
}
else {
   print("letters not found")
}
2.2
let letters = NSCharacterSet.letterCharacterSet()

let phrase = "Test case"
let range = phrase.rangeOfCharacterFromSet(letters)

// range will be nil if no letters is found
if let test = range {
   print("letters found")
}
else {
  print("letters not found")
}

The new CharacterSet struct that is also bridged to the Objective-C NSCharacterSet class define several predefined sets as:

  • decimalDigits
  • capitalizedLetters
  • alphanumerics
  • controlCharacters
  • illegalCharacters
  • and more you can find in the NSCharacterSet reference.

You also can define your own set of characters:

3.0
let phrase = "Test case"
let charset = CharacterSet(charactersIn: "t")

if let _ = phrase.rangeOfCharacter(from: charset, options: .caseInsensitive) {
   print("yes") 
}
else {
   print("no")
}
2.2
let charset = NSCharacterSet(charactersInString: "t")

if let _ = phrase.rangeOfCharacterFromSet(charset, options: .CaseInsensitiveSearch, range: nil) {
   print("yes")
}
else {
    print("no")
}

You can also include range:

3.0
let phrase = "Test case"
let charset = CharacterSet(charactersIn: "t")

if let _ = phrase.rangeOfCharacter(from: charset, options: .caseInsensitive, range: phrase.startIndex..<phrase.endIndex)) {
   print("yes") 
}
else {
   print("no")
}