String Fundamentals
Before we get into how to use strings, we will cover why they are the way they are. For developers coming from other languages, this is a very reasonable question to ask.
Character
We won't go into the details of Unicode, but there are several ways of viewing a piece of Unicode text in Swift. This is done by using different collections:
let string = "The ☀ and 🌙" string.utf8.count // 19 string.utf16.count // 13 string.unicodeScalars.count // 12
Note
An element of UTF-8 is 1 byte, UTF-16 is 2 bytes, and a Unicode scalar is 4 bytes.
In addition to everyone reporting a different number of symbols in the string, you may have also noticed that they are all wrong. String
itself, however, has the right answer:
string.count // 11
This is because ...
Get Beginning Swift now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.