Swift Characters
Character is one user-visible character.
Strings are collections of characters.
Characters and String Length
Use Character for single letters.
Use String.count to get the number of characters.
Example
let ch: Character = "A"
print(ch)
let word = "Swift"
print(word.count)
This prints a character and a string length.
Characters and String Conversion
Convert between Character and String as needed.
Example
let ch: Character = "A"
let s = String(ch)
print(s) // "A"
Unicode and Grapheme Clusters
Some characters use multiple Unicode scalars but still count as one character.
Example
let heart: Character = "❤️"
print(heart)
let flag: Character = "🇳🇴" // composed of two regional indicators
print(flag)
print("e\u{301}".count) // 1 (e + combining acute accent)
Leave a Reply