I'm trying to filter non-alphabetical characters out of a String, but running into the issue that CharacterSet
uses Unicode.Scalar
and String consists of Character
.
Xcode gives the error:
Cannot convert value of type 'String.Element' (aka 'Character') to specified type 'Unicode.Scalar?'
let name = "name"
let allowedCharacters = CharacterSet.alphanumerics
let filteredName = name.filter { (c) -> Bool in
if let s: Unicode.Scalar = c { // cannot convert
return !allowedCharacters.contains(s)
}
return true
}
CharacterSet
has an unfortunate name inherited from Objective C. In reality, it is a set of Unicode.Scalar
s, not of Characters
(“extended grapheme clusters” in Unicode parlance). This is necessary, because while there is a finite set of Unicode scalars, there is an infinite number of possible grapheme clusters. For example, e + ◌̄ + ◌̄ + ◌̄ ...
ad infinitum is still just one cluster. As such, it is impossible to exhaustively list all possible clusters, and it is often impossible to list the subset of them that has a particular property. Set operations such as those in the question must use scalars instead (or at least use definitions derived from the component scalars).
In Swift, String
s have a unicodeScalars
property for operating on the string a the scalar level, and the property is directly mutable. That enables you to do things like this:
// Assuming...
var name: String = "..."
// ...then...
name.unicodeScalars.removeAll(where: { !CharacterSet.alphanumerics.contains($0) })