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

前端 未结 11 1729
南旧
南旧 2020-11-30 01:03

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

11条回答
  •  情话喂你
    2020-11-30 01:52

    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:)

提交回复
热议问题