Swift in Depth
eBook - ePub

Swift in Depth

Tjeerd in 't Veen

Partager le livre
  1. English
  2. ePUB (adapté aux mobiles)
  3. Disponible sur iOS et Android
eBook - ePub

Swift in Depth

Tjeerd in 't Veen

DĂ©tails du livre
Aperçu du livre
Table des matiĂšres
Citations

À propos de ce livre

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!

Foire aux questions

Comment puis-je résilier mon abonnement ?
Il vous suffit de vous rendre dans la section compte dans paramĂštres et de cliquer sur « RĂ©silier l’abonnement ». C’est aussi simple que cela ! Une fois que vous aurez rĂ©siliĂ© votre abonnement, il restera actif pour le reste de la pĂ©riode pour laquelle vous avez payĂ©. DĂ©couvrez-en plus ici.
Puis-je / comment puis-je télécharger des livres ?
Pour le moment, tous nos livres en format ePub adaptĂ©s aux mobiles peuvent ĂȘtre tĂ©lĂ©chargĂ©s via l’application. La plupart de nos PDF sont Ă©galement disponibles en tĂ©lĂ©chargement et les autres seront tĂ©lĂ©chargeables trĂšs prochainement. DĂ©couvrez-en plus ici.
Quelle est la différence entre les formules tarifaires ?
Les deux abonnements vous donnent un accĂšs complet Ă  la bibliothĂšque et Ă  toutes les fonctionnalitĂ©s de Perlego. Les seules diffĂ©rences sont les tarifs ainsi que la pĂ©riode d’abonnement : avec l’abonnement annuel, vous Ă©conomiserez environ 30 % par rapport Ă  12 mois d’abonnement mensuel.
Qu’est-ce que Perlego ?
Nous sommes un service d’abonnement Ă  des ouvrages universitaires en ligne, oĂč vous pouvez accĂ©der Ă  toute une bibliothĂšque pour un prix infĂ©rieur Ă  celui d’un seul livre par mois. Avec plus d’un million de livres sur plus de 1 000 sujets, nous avons ce qu’il vous faut ! DĂ©couvrez-en plus ici.
Prenez-vous en charge la synthÚse vocale ?
Recherchez le symbole Écouter sur votre prochain livre pour voir si vous pouvez l’écouter. L’outil Écouter lit le texte Ă  haute voix pour vous, en surlignant le passage qui est en cours de lecture. Vous pouvez le mettre sur pause, l’accĂ©lĂ©rer ou le ralentir. DĂ©couvrez-en plus ici.
Est-ce que Swift in Depth est un PDF/ePUB en ligne ?
Oui, vous pouvez accĂ©der Ă  Swift in Depth par Tjeerd in 't Veen en format PDF et/ou ePUB ainsi qu’à d’autres livres populaires dans Computer Science et Programming. Nous disposons de plus d’un million d’ouvrages Ă  dĂ©couvrir dans notre catalogue.

Informations

Année
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 des matiĂšres