Letters
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")
}
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
You also can define your own set of characters:
let phrase = "Test case"
let charset = CharacterSet(charactersIn: "t")
if let _ = phrase.rangeOfCharacter(from: charset, options: .caseInsensitive) {
print("yes")
}
else {
print("no")
}
let charset = NSCharacterSet(charactersInString: "t")
if let _ = phrase.rangeOfCharacterFromSet(charset, options: .CaseInsensitiveSearch, range: nil) {
print("yes")
}
else {
print("no")
}
You can also include range:
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")
}