Swift in Depth
eBook - ePub

Swift in Depth

Tjeerd in 't Veen

Share book
  1. English
  2. ePUB (mobile friendly)
  3. Available on iOS & Android
eBook - ePub

Swift in Depth

Tjeerd in 't Veen

Book details
Book preview
Table of contents
Citations

About This Book

Now updated for Swift 5! Swift is more than just a fun language to build iOS applications with. It features a host of powerful tools that, if effectively used, can help you create even better apps with clean, crystal-clear code and awesome features. Swift in Depth is designed to help you unlock these tools and quirks and get developing next-gen apps, web services, and more!

Frequently asked questions

How do I cancel my subscription?
Simply head over to the account section in settings and click on “Cancel Subscription” - it’s as simple as that. After you cancel, your membership will stay active for the remainder of the time you’ve paid for. Learn more here.
Can/how do I download books?
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
What is the difference between the pricing plans?
Both plans give you full access to the library and all of Perlego’s features. The only differences are the price and subscription period: With the annual plan you’ll save around 30% compared to 12 months on the monthly plan.
What is Perlego?
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Do you support text-to-speech?
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Is Swift in Depth an online PDF/ePUB?
Yes, you can access Swift in Depth by Tjeerd in 't Veen in PDF and/or ePUB format, as well as other popular books in Computer Science & Programming. We have over one million books available in our catalogue for you to explore.

Information

Year
2018
ISBN
9781617295188

Chapter 1. Introducing Swift in depth

In this chapter
  • A brief overview of Swift’s popularity and supported platforms
  • The benefits of Swift
  • A closer look at Swift’s subtle downsides
  • What we will learn in this book
It is no secret that Swift is supported on many platforms, such as Apple’s iOS, macOS, watchOS, and tvOS. Swift is open source and also runs on Linux, and it’s gaining popularity on the server side with web frameworks such as Vapor, Perfect, Zewo, and IBM’s Kitura.
On top of that, Swift is slowly not only encompassing application programming (software for users) but also starting to enter systems programming (software for systems), such as SwiftNIO or command-line tools. Swift is maturing into a multi-platform language. By learning Swift, many doors open to you.
Swift was the most popular language on Stack overflow in 2015 and remains in the top five most-loved languages in 2017. In 2018, Swift bumped to number 6 (https://insights.stackoverflow.com/survey/2018).
Swift is clearly here to stay, and whether you love to create apps, web services, or other programs, I aim for you to get as much value as possible out of this book for both yourself and any team you’re on.
What I love about Swift is that it’s easy to learn, yet hard to master. There’s always more to learn! One of the reasons is that Swift embraces many programming paradigms, allowing you to pick a suitable solution to a programming problem, which you’re going to explore in this book.

1.1. The sweet spot of Swift

One thing I love about a dynamic language—such as Ruby—is its expressive nature. Your code tells you what you want to achieve without getting too much in the way of memory management and low-level technology. Writing in Ruby one day, and Objective-C the other, made me believe that I either had to pick between a compiled language that performed well or an expressive, dynamic language at the cost of lower performance.
Then Swift came out and broke this fallacy. Swift finds the right balance where it shares many benefits of dynamic languages—such as Ruby or Python—by offering a friendly syntax and strong polymorphism. Still, Swift avoids some of the downsides of dynamic languages, most notably the performance, because Swift compiles to native machine code via the LLVM compiler. Because Swift is compiled via LLVM, you get not only high performance, but also tons of safety checks, optimizations, and the guarantee that your code is okay before even running it. At the same time, Swift reads like an expressive dynamic language, making it pleasant to work with and effortless to express your intent.
Swift can’t stop you from writing bugs or poor code, but it does help reduce program errors at compile time using various techniques, including, but not limited to, static typing and strong support for algebraic data types (enums, structs, and tuples). Swift also prevents null errors thanks to optionals.
A downside of some static languages is that you always need to define the types. Swift makes this easier via type inference and can deduce concrete types when it makes sense. This way, you don’t need to explicitly spell out every single variable, constant, and generic.
Swift is a mixtape of different programming paradigms, because whether you take an object-oriented approach, functional programming approach, or are used to working with abstract code, Swift offers it all. As the major selling point, Swift has a robust system when it comes down to polymorphism, in the shape of generics and protocol-oriented programming, which gets pushed hard as a marketing tool, both by Apple and developers (see figure 1.1).
Figure 1.1. The sweet spot of Swift

1.2. Below the surface

Even though Swift reels you in with its friendly syntax and promises to build amazing apps, it’s merely the tip of the iceberg. An enticing entry to learning Swift is to start with iOS development, because not only will you learn about Swift, you will also learn how to create beautiful apps that are composed of crucial components from Apple frameworks.
But as soon as you need to deliver components yourself and start building more elaborate systems and frameworks, you will learn that Swift works hard to hide many complexities—and does so successfully. When you need to learn these complexities, and you will, Swift’s difficulty curve goes up exponentially. Even the most experienced developers are still learning new Swift tricks and tidbits every day!
Once Swift has you hooked, you’ll likely hit speed bumps in the shape of generics and associated types, and something as “simple” as handling strings may cause more trouble than you might expect (see figure 1.2).
Figure 1.2. The tip of Swift’s iceberg
This book shines in helping you handle the most common complexities. You will cover and tackle any issues and shortcomings with Swift, and you’ll be able to wield the powers that these complexities bring while having fun doing so.

1.3. Swift’s downsides

Swift is my favorite programming language, but let’s not look at it through rose-tinted glasses. Once you acknowledge both Swift’s strong and weak points, you can adequately decide when and how you’d like to use it.

1.3.1. Module stability

Swift is still moving fast and is not module-stable, which means that a framework offered in one version needs to be recompiled for a newer Swift version. Imagine writing a framework for your application. As soon as Swift 6 comes out, an application written in Swift 6 can’t use your framework until you’ve updated your framework to Swift 6. Luckily, Xcode offers plenty of help to migrate, so I expect that this migration won’t be as painful.

1.3.2. Strictness

Swift is a strict and rigid language, which is a common criticism of static languages but even more so when working with Swift. Before getting comfortable with Swift, you may feel like you’re typing with handcuffs on. In practice, you have to resolve many types at compile-time, such as using optionals, mixing values in collections, or handling enums.
I would argue that Swift’s strict nature is one of its strong selling points. As soon as you try to compile, you learn of code that isn’t working as opposed to having a customer run into a runtime error. Once you’ve made the initial investment to get comfortable with Swift, it will come naturally, and its restrictiveness will stop you less. This book helps you get over the hump, so that Swift becomes second nature.

1.3.3. Protocols are tricky

Protocols are the big selling point of Swift. But once you start working with protocols, you will hit sharp edges and cut yourself from time to time. Things that “should just work” somehow don’t. Protocols are great in their current state and already good enough for creating quality software, but sometimes you hit a wall, and you’ll have to use workarounds—of which this book shares plenty.
A common source of frustration: if you’d like to pass Equatable types to a function to see if they are equal, you get stopped. For instance, you might naively try checking if one value is equal to everything inside an array, as shown in the next listing. You will learn that this won’t fly in Swift.
Listing 1.1. Trying to equate to types
areAllEqual(value: 2, values: [3,3,3,3]) func areAllEqual(value: Equatable, values: [Equatable]) -> Bool { guard !values.isEmpty else { return false } for element in values { if element != value { return false } } return true }
Swift returns a cryptic error with a vague suggestion on what to do:
error: protocol 'Equatable' can only be used as a generic constraint because it has Self or associated type requirements
You’ll see why this happens and how to avoid these issues in chapters 7 and 8.
Swift’s protocol extensions are another of its major selling points and are one of the most powerful features it has to offer. Protocols can act like interfaces; protocol extensions offer default implementations to types, helping you avoid rigid subclassing trees.
Protocols, however, are trickier than they may seem and may surprise even the seasoned developer. For instance, let’s say you have a protocol called FlavorType representing a food or drink item that you can improve with flavor, such as coffee. If you extend this protocol with a default implementation that is not found inside the protocol declaration, you may get surprising results! Notice in the next listing how you have two Coffee types, yet they both yield different results when calling addFlavor on them. It’s a subtle but significant detail.
Listing 1.2. Protocols can surprise us
protocol FlavorType{ // func addFlavor() // You get different results if this method doesn't exist. } extension FlavorType { func addFlavor() { // Create a default implementation. print("Adding salt!") } } struct Coffee: FlavorType { func addFlavor() { // Coffee supplies its own implementation. print("Adding cocoa powder") } } let tastyCoffee: Coffee = Coffee() // tastyCoffee is of type 'Coffee' tastyCoffee.addFlavor() // Adding cocoa powder let grossCoffee: FlavorType = tastyCoffee // grossCoffee is of type FlavorType grossCoffee.addFlavor() // Adding salt!
Even though you’re dealing with the same coffee type, first you add cocoa powder, and then you accidentally add salt, which doesn’t help anyone get up in the morning. As powerful as protocols are, they can introduce subtle bugs sometimes.

1.3.4. Concurrency

Our computers and devices are concurrent machines, utilizing multiple CPUs simultaneously. When working in Swift you are already able to express concurrent code via Apple’s Grand Central Dispatch (GCD). But concurrency doesn’t exist in Swift as a langua...

Table of contents