This is a book for complete beginners to Apple’s modern programming language — Swift.
All the code in the book works inside of Xcode’s easy-to-use playgrounds. That means you can focus on core Swift language concepts, such as classes, protocols, and generics, instead of getting bogged down in the details of building apps.
This is a companion book to the SwiftUI Apprentice; the SwiftUI Apprentice focuses on building apps, while Swift Apprentice focuses on the Swift language itself.
Before You Begin
This section tells you a few things you need to know before you get started, such as what you’ll need for hardware and software, where to find the project files for this book and more.
The chapters in this section will introduce you to the very basics of programming in Swift. From the fundamentals of how computers work up to language structures, you’ll cover enough of the language to be able to work with data and organize your code’s behavior.
The section begins with some groundwork to get you started.
Once you have the basic data types in your head, it’ll be time to do things with that data, and finally, you’ll learn about an essential data type, optionals, that let you express potentially missing data.
These fundamentals will get you Swiftly on your way, and before you know it, you’ll be ready for the more advanced topics that follow. Let’s get started!
This is it, your whirlwind introduction to the world of programming! You’ll begin with an overview of computers and programming and then say hello to Swift playgrounds, which are where you’ll spend your coding time for the rest of this book.
You’ll learn some basics such as code comments, arithmetic operations, constants and variables. These are some of the fundamental building blocks of any language, and Swift is no different.
You’ll learn about handling different types, including strings that allow you to represent text.
You’ll learn about converting between types, and you’ll also get an introduction to type inference, which makes your life as a programmer a lot simpler.
You’ll learn about tuple types which allow you to group values of any type together.
You’ll learn how to make decisions and repeat tasks in your programs using syntax to control the flow.
You’ll also learn about Booleans, which represent true and false values, and how you can use these to compare data.
This chapter covers optionals, a special type in Swift that represents either a real value or the absence of a value. By the end of this chapter, you’ll know why you need optionals and how to use them safely.
Section II: Collection Types
So far, you’ve mostly seen data in the form of single elements. Although tuples can have multiple pieces of data, you have to specify the size upfront; a tuple with three strings is a completely different type from a tuple with two strings, and converting between them isn’t trivial. In this section, you’ll learn about collection types in Swift. Collections are flexible “containers” that let you store any number of values together.
There are several collection types in Swift, but three important ones are arrays, dictionaries and sets. You’ll learn to apply custom operations and loop over collection types. Finally, you’ll revisit strings, which are collections of characters.
All the collection types share similar interfaces but have very different use cases. As you read through these chapters, keep the differences in mind, and you’ll begin to develop a feel for which type you should use when.
Arrays are the most common collection type you’ll run into in Swift that keep an ordered list of elements of the same type. On the other hand, Dictionaries let you look up elements efficiently using a key. Finally, Sets maintain an unordered collection of unique elements. You’ll learn all about these three types in this chapter.
Once you have collections of items, you will want to perform operations with them.
For example, sort them, filter them, add them up, etc. Swift gives you a powerful
language construct, the closure, that lets you infinitely customize the behavior
of such operations. In this chapter, you will learn about Swift's most common
collection algorithms and customize them with closures.
Text processing is an essential application for any computer language, and String is Swift’s powerhouse type for text handling. Strings are bi-directional collections of Character types that balance correctness, performance and ease of use.
Section III: Building Your Own Types
You can create your own type by combining variables and functions into a new type definition. When you create a new type, you give it a name; thus, these custom types are known as named types. Structures are a powerful tool for modeling real-world concepts. You can encapsulate related concepts, properties and methods into a single, cohesive model.
Swift includes four kinds of named types: structures, classes, enumerations and protocols. You’ll learn here how other named types use the concepts of methods and properties, how they differ, and where you want to use each.
You’ll also learn about generics, which are types and methods that take as input other types instead of just methods, as well as custom types to build larger and complex things!
The standard library has many useful types like Int, Double and String. However, it sadly does not include a Pizza type. Structures are types that can store named properties and define actions and behaviors. You will define your own custom structure types in this chapter and begin building a Pizza empire.
Structures let you define your own named types with custom properties and methods. In this chapter, you’ll get acquainted with classes, which are much like structures but have important differences that you will learn about.
This chapter continues with class types describing how Swift supports the traditional concepts of inheritance and polymorphism. You will also learn about two-phase class initialization that you will need to build proper class hierarchies. This discussion will lay the foundation for using these concepts with Swift’s value types.
In this chapter, you'll learn about enumerations, a type that groups related, mutually exclusive case values. You’ll also learn about uninhabited types and finally discover what an optional is under the hood.
Protocols are a type that can bridge common behaviors between structs,
classes, and enums by defining an interface or template for an actual concrete type.
Protocols overcome the single inheritance limitation that you saw with classes.
In this chapter, you’ll learn what generics are, learn how to write your own generic code, and loop back and look at the generic types in Swift - dictionaries, arrays, and optionals - from this new perspective.
Section IV: Advanced Topics
You’ve made it to the final section of this book! In this section, you’ll delve into some essential but more advanced topics to round out your Swift apprenticeship.
After reading this section, you’ll be on your way to being a knowledgable Swift developer by digging into topics even those most advanced programmers use.
You’ll learn to hide complexity in your apps and organize your code through access control and testing tools. You’ll also work on pattern matching, error handling, and memory management, as well as encoding and decoding types. You will also get exposure to the newest language features, including result builders and property wrappers which drive cutting-edge frameworks like SwiftUI.
And level up how you approach your code by customizing operators and subscripts and leveraging protocol-oriented programming while using constraints to make generic code more functional.
Finally, you will get in-depth exposure to Swift’s native concurrency features, which improve the correctness, safety and efficiency of writing concurrent code.
Swift gives you powerful tools for hiding complexity and organizing your code into easier-to-digest units. As your codebase grows,
ensuring correctness with automated tests becomes more critical in your projects.
You’ll learn how you can define your own operators and subscripts to make your types feel even more like built-in language constructs.
Keypaths provide references to properties, and together with subscripts and dynamic member lookup, you can do amazing things.
Swift is a concise, powerful language, but for specific tasks, it can seem too verbose. Result builders allow you to create a domain-specific language, letting you compactly express complex values. In this chapter, you will implement a result builder for making fancy attributed strings.
With pattern matching, you can accomplish more with less typing, and it helps give Swift its modern language feel. This chapter picks up where Chapter 4, "Advanced Flow Control", left off and shows you powerful Swift idioms that let you work with switch-statements, tuples, optionals and more.
In the real world, you can’t avoid some errors. Gracefully handling errors is what sets mediocre code apart from great code. From handling missing values and simple initialization failure with optionals to providing greater diagnostic detail using full-featured error types, Swift provides language features to make your code robust and informative in the face of errors.
Swift has a powerful system for saving and loading your types to and from, for example, a file system, over the internet or some other communication channel. Swift has exceptional out-of-the-box support for the JSON format that you will become familiar with in this chapter.
Used widely in frameworks like Apple’s SwiftUI and Vapor, property wrappers are a general-purpose language feature for building reusable, custom logic that defines how a property behaves. This chapter develops an advanced example and highlights some pitfalls to avoid.
From the standard library to user-authored generics, Swift is a protocol-based language.
In this chapter, you’ll see how to get all of the benefits associated
with object-oriented programming while being able to avoid most of the difficulties.
Swift concurrency is a new way to handle asynchronous and concurrent code. It implements structured concurrency and provides language features that check many aspects of your code at compile time. In this chapter, you'll learn about these mechanisms and how actors protect the shared mutable state of your objects without needing a lot of error-prone, boilerplate code.
Ray Fix works on next-generation microscopes made for iPad at Discover Echo Inc. in San Diego, California. Ray enjoys learning...
Who is this book for
This is a book for complete beginners to Apple’s modern programming language — Swift.
Concepts covered in this book
All the code in the book works inside of Xcode’s easy-to-use playgrounds.
That means you can focus on core Swift language concepts, such as classes, protocols,
and generics, instead of getting bogged down in the details of building apps.
This is a companion book to the SwiftUI Apprentice;
the SwiftUI Apprentice focuses on building apps, while Swift Apprentice focuses
on the Swift language itself.
Seventh Edition · iOS 15, Swift 5.5, Xcode 13
v7.0 · Oct 27 2021 · Cosmin Pupăză, Ben Morrow, Eli Ganim, Alexis Gallagher, Ehab Yosry Amer & Matt Galloway