What is the best way to determine if a string contains a character from a set in Swift

You can create a CharacterSet containing the set of your custom characters and then test the membership against this character set:

Swift 3:

let charset = CharacterSet(charactersIn: "aw")
if str.rangeOfCharacter(from: charset) != nil {
    print("yes")
}

For case-insensitive comparison, use

if str.lowercased().rangeOfCharacter(from: charset) != nil {
    print("yes")
}

(assuming that the character set contains only lowercase letters).

Swift 2:

let charset = NSCharacterSet(charactersInString: "aw")
if str.rangeOfCharacterFromSet(charset) != nil {
    print("yes")
}

Swift 1.2

let charset = NSCharacterSet(charactersInString: "aw")
if str.rangeOfCharacterFromSet(charset, options: nil, range: nil) != nil {
    println("yes")
}

ONE LINE Swift4 solution to check if contains letters:

CharacterSet.letters.isSuperset(of: CharacterSet(charactersIn: myString) // returns BOOL

Another case when you need to validate string for custom char sets. For example if string contains only letters and (for example) dashes and spaces:

let customSet: CharacterSet = [" ", "-"]
let finalSet = CharacterSet.letters.union(customSet)
finalSet.isSuperset(of: CharacterSet(charactersIn: myString)) // BOOL

Hope it helps someone one day:)


From Swift 1.2 you can do that using Set

var str = "Hello, World!"
let charset: Set<Character> = ["e", "n"]

charset.isSubsetOf(str)     // `true` if `str` contains all characters in `charset`
charset.isDisjointWith(str) // `true` if `str` does not contains any characters in `charset`
charset.intersect(str)      // set of characters both `str` and `charset` contains.

Swift 3 or later

let isSubset = charset.isSubset(of: str)        // `true` if `str` contains all characters in `charset`
let isDisjoint = charset.isDisjoint(with: str)  // `true` if `str` does not contains any characters in `charset`
let intersection = charset.intersection(str)    // set of characters both `str` and `charset` contains.
print(intersection.count)   // 1

Tags:

Swift