Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Beginning Swift

You're reading from   Beginning Swift Master the fundamentals of programming in Swift 4

Arrow left icon
Product type Paperback
Published in May 2018
Publisher Packt
ISBN-13 9781789534313
Length 202 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Rob Kerr Rob Kerr
Author Profile Icon Rob Kerr
Rob Kerr
Kåre Morstøl Kåre Morstøl
Author Profile Icon Kåre Morstøl
Kåre Morstøl
Arrow right icon
View More author details
Toc

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: ...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime