1

Trying to determine if an input string is a valid phone number using CharacterSet. Seems that isSubset works fine, but isSuperset will crash.

I think this is a bug in Foundation.

let phoneNumberCharacterSet = CharacterSet(charactersIn: "01234567890,;*+#").union(CharacterSet.whitespaces)
let zeroCharacterSet = CharacterSet(charactersIn: "0")

if zeroCharacterSet.isSubset(of: phoneNumberCharacterSet) {
    print("zero is a subset of the phone number set")
}

if phoneNumberCharacterSet.isSuperset(of: zeroCharacterSet) {
    // will never get here due to crash
    print("is a superset of '0'")
}
Ric Santos
  • 15,419
  • 6
  • 50
  • 75

1 Answers1

0

According to this

Seems the current bridging of CharacterSet generates something weird which does not work with isSuperset(of:). (It internally calls CFCharacterSetIsSupersetOfSet(_:_:).)

You can get

if phoneNumberCharacterSet.isSuperset(of: zeroCharacterSet) {
    // will never get here due to crash
    print("is a superset of '0'")
}

replaced by

let zeroString = "0"
if zeroString.rangeOfCharacter(from: phoneNumberCharacterSet.inverted) == nil {
    print("is a superset of '0'")
}
Lawliet
  • 3,438
  • 2
  • 17
  • 28