Book Image

Beginning Swift

By : Rob Kerr, Kåre Morstøl
Book Image

Beginning Swift

By: Rob Kerr, Kåre Morstøl

Overview of this book

Take your first foray into programming for Apple devices with Swift.Swift is fundamentally different from Objective-C, as it is a protocol-oriented language. While you can still write normal object-oriented code in Swift, it requires a new way of thinking to take advantage of its powerful features and a solid understanding of the basics to become productive.
Table of Contents (10 chapters)

String Fundamentals


Before we get into how to use strings, we will cover why they are the way they are. Because 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 String is an ordered collection of Character. Character represents what we humans would consider one symbol, regardless of how many bytes it consists of.

The reason for the discrepancies is, of course, the two emojis: ...