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

前端 未结 11 1712
南旧
南旧 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:46

    From Swift 1.2 you can do that using Set

    var str = "Hello, World!"
    let charset: Set = ["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
    

提交回复
热议问题