Swift: Check if first character of String is ASCII or a letter with an accent

2.9k Views Asked by At

In Swift, how do I check whether the first character of a String is ASCII or a letter with an accent? Wider characters, like emoticons & logograms, don't count.

I'm trying to copy how the iPhone Messages app shows a person's initials beside their message in a group chat. But, it doesn't include an initial if it's an emoticon or a Chinese character for example.

I see decomposableCharacterSet & nonBaseCharacterSet, but I'm not sure if those are what I want.

1

There are 1 best solutions below

0
On

There are many Unicode Character with an accent. Is this for you a character with an accent?

Ê Ð Ï Ḝ Ṹ é⃝


In Unicode there are combined characters, which are two unicode characters as one:

let eAcute: Character = "\u{E9}"                         // é
let combinedEAcute: Character = "\u{65}\u{301}"          // e followed by ́
// eAcute is é, combinedEAcute is é

For Swift the Character is the same!

Good reference is here.


If you want to know the CodeUnit of the Characters in the String, you can use the utf8 or utf16 property. They are different!

let characterString: String = "abc"
for character in characterString.utf8 {
    print("\(character) ")
}
// output are decimal numbers: 97 98 99 
// output of only é: 195 169, used the combined é

Then you could check for ASCII alphabet A-Z as 65-90 and a-z as 97-122. And then check for the standard accent grave and acute À 192 Á 193 È 200 É 201 à 224 á 225 è 232 é 233 ... and the combined ones and everything you like.

But there are symbols that look like a latin letter with accent, but doesn't have the same meaning!

You should make sure, that only these characters are accepted, that you want with the correct linguistic meaning.