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
Question was specifically: "if a string contains any of the characters from a custom set" and not checking for all characters in the custom set.
Using
func check(in string: String, forAnyIn characters: String) -> Bool {
// create one character set
let customSet = CharacterSet(charactersIn: characters)
// use the rangeOfCharacter(from: CharacterSet) function
return string.rangeOfCharacter(from: customSet) != nil
}
check(in: "abc", forAnyIn: "A") // false
check(in: "abc", forAnyIn: "b") // true
But this is also very easy to check using character sets.
func check(in string: String, forAnyIn characters: String) -> Bool {
let customSet = CharacterSet(charactersIn: characters)
let inputSet = CharacterSet(charactersIn: string)
return !inputSet.intersection(customSet).isEmpty
}
check(in: "abc", forAnyIn: "A") // false
check(in: "abc", forAnyIn: "b") // true