eBook - ePub
Swift in Depth
Tjeerd in 't Veen
This is a test
Partager le livre
- English
- ePUB (adapté aux mobiles)
- 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
Sujet
Computer ScienceSous-sujet
ProgrammingChapter 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...