mattnedrich mattnedrich - 4 months ago 7x
Swift Question

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

I need to determine if a string contains any of the characters from a custom set that I have defined.

I see from this post that you can use rangeOfString to determine if a string contains another string. This, of course, also works for characters if you test each character one at a time.

I'm wondering what the best way to do this is.


You could create a NSCharacterSet containing the set of your custom characters:

let charset = NSCharacterSet(charactersInString: "aw")

and then test the membership against this character set:

if str.lowercaseString.rangeOfCharacterFromSet(charset, options: nil, range: nil) != nil {