I was trying to user CharacterSet to check if a user input string contains any non decimal digit characters. I use CharacterSet.decimalDigits
and take the intersection of that with the user input. If this intersection is empty, it presumably means the user hasn't entered valid input. Yet the intersection is not empty.
let digits = CharacterSet.decimalDigits
let letters = CharacterSet(charactersIn: "abcd") // never prints
let intersection = digits.intersection(letters)
for c in "abcd".characters {
if intersection.contains(UnicodeScalar(String(c))!) {
print("contains \(c)") // never prints
}
}
for i in 0...9 {
if intersection.contains(UnicodeScalar(String(i))!) {
print("contains \(i)")
}
}
print("intersection is empty: \(intersection.isEmpty)") // prints false
I even tried looping over all unicode scalars to test for membership, and that doesn't print anything.
for i in 0x0000...0xFFFF {
guard let c = UnicodeScalar(i) else {
continue
}
if intersection.contains(c) {
print("contains \(c)")
}
}
Why is the set non empty?
Note Using let digits = CharacterSet(charactersIn: "1234567890")
works as expected. I know that the decimalDigits
contains more than just 0-9, but the intersection should still be empty.