Are there any opinions on the best or correct way to check that a Character
is in CharacterSet
?
EDIT: It occurred to me after posting I should probably say that "best" is not quantifiable. So maybe I could add performant. Really I'm just looking to get some discussion about different approaches.
My confusion comes about because CharacterSet.contains
takes a Unicode.Scalar
instead of a CharacterSet
. This is simultaneously expected and not very ergonomic.
For example, say that you are tasked with getting the sequential Character
s of a String
that belong to a CharacterSet
. For this example get all the lowercase letters.
So far, I think this is my best answer. Though I'm not super jazzed about, what at least feels like even if it is not really, nested loops.
let str = "hellọ̀, playground"
let charset = CharacterSet.lowercaseLetters
let prefix = str.prefix(while: { $0.unicodeScalars.first(where: { charset.contains($0) }) != nil })
print(prefix) // hellọ̀
I tried this one too. Though as you can see it is not technically correct (it is missing the acute on the o).
let str = "hellọ̀, playground"
let charset = CharacterSet.lowercaseLetters
let unicodePrefix = str.unicodeScalars.prefix(while: { charset.contains($0) })
print(String(unicodePrefix)) // hellọ
Maybe it feels un-ergonomic because I'm using the wrong APIs?