📄 Page
1
(This page has no text content)
📄 Page
2
Other books in O’Reilly’s Head First series Head First Android Development Head First C# Head First Design Patterns Head First Git Head First Go Head First iPhone and iPad Development Head First Java Head First JavaScript Programming Head First Learn to Code Head First Object-Oriented Analysis and Design Head First Programming Head First Python Head First Software Development Head First Web Design
📄 Page
3
Head First Swift A Learner’s Guide to Programming with Swift Paris Buttfield-Addison and Jon Manning
📄 Page
4
Head First Swift by Paris Buttfield-Addison and Jon Manning Copyright © 2021 Secret Lab. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://oreilly.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com. Series Creators: Kathy Sierra, Bert Bates Acquisitions Editor: Suzanne McQuade Development Editor: Michele Cronin Production Editor: Christopher Faucher Brain Image on Spine: Eric Freeman Proofreader: Rachel Head Indexer: Potomac Indexing, LLC Cover Designer: Karen Montgomery Page Viewers: Mars Buttfield-Addison, Argos and Apollo (dogs) November 2021: First Edition Revision History
📄 Page
5
2021-11-17: First Early Release See http://oreilly.com/catalog/errata.csp?isbn=9781491922859 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. The Head First series designations, Head First Swift, and related trade dress are trademarks of O’Reilly Media, Inc. Head First Swift is an independent publication and has not been authorized, sponsored, or otherwise approved by Apple Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trademark claim, the designations have been printed in caps or initial caps. Apple, the Apple logo, iOS, iPadOS, macOS, Mac, Xcode, Swift Playgrounds, SwiftUI, watchOS, tvOS, iPad, iPhone, iPod, and iPod touch are trademarks of Apple Inc., registered in the U.S. and other countries. Swift and the Swift logo are trademarks of Apple Inc. While every precaution has been taken in the preparation of this book, the publisher and the authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. No parrots, robots, or chefs were harmed in the making of this book. 978-1-492-05825-0 LSI
📄 Page
6
Authors of Head First Swift Paris Buttfield-Addison and Jon Manning are the cofounders of Hobart, Tasmania, Australia–based video game development studio Secret Lab. Both Paris and Jon have PhDs in computer science, and between them they’ve written around 30 technical books over the years. They worked together at the influential “Web 2.0”–era startup Meebo, and are part of the team behind one of the longest-running Apple-related developer conferences, AUC /dev/world. Paris and Jon have worked on thousands of apps and games at Secret Lab. They’re best known for the adventure game Night in the Woods, which won an Independent Game Festival award and a BAFTA, as well as their popular open source project Yarn Spinner at https://yarnspinner.dev, which powers thousands of narrative video games. Paris and Jon both live and work in Hobart and enjoy photography, cooking, and giving far too many conference talks. Find Paris on Twitter @parisba and online at https://paris.id.au, Jon on Twitter @desplesda and online at https://desplesda.net, and Secret Lab on Twitter at @thesecretlab and online at https://secretlab.games.
📄 Page
7
(This page has no text content)
📄 Page
8
Table of Contents (the real thing) 1. how to use this book: Intro Your brain on Swift. Here you are trying to learn something, while here your brain is doing you a favor by making sure the learning doesn’t stick. Your brain’s thinking, “Better leave room for more important things, like which wild animals to avoid and whether naked snowboarding is a bad idea.” So how do you trick your brain into thinking that your life depends on knowing Swift? a. “Who is this book for?” b. “We know what you’re thinking” c. “We know what your brain is thinking” d. “Metacognition: thinking about thinking” e. “Here’s what WE did” f. “Here’s what YOU can do to bend your brain into submission” g. “Read me” h. “The technical review team” i. “Acknowledgments” 2. Chapter 1 Swift is a programming language you can rely on. It’s a programming language you can take home to meet your family. Safe, reliable, speedy, friendly, easy to talk to. And while Swift is best known for being the programming language of choice for
📄 Page
9
Apple’s platforms, such as iOS, macOS, watchOS, and tvOS, the open source Swift project also runs on Linux and Windows, and is gaining ground as a systems programming language, as well as on the server. You can build everything from mobile apps, to games, to web apps, to frameworks and beyond. Let’s get started! a. “Swift is a language for everything” b. “The swift evolution of Swift” c. “Swift into the future” d. “How you’re going to write Swift” e. “The path you’ll be taking” f. “Getting Playgrounds” g. “Creating a Playground” h. “Using a Playground to code Swift” i. “Basic building blocks” j. “A Swift example” k. “Congrats on your first steps with Swift!” 3. Chapter 2 You already know the gist of Swift. But it’s time to dive into the building blocks in more detail. You’ve seen enough Swift to be dangerous, and it’s time to put it into practice. You’ll use Playgrounds to write some code, using statements, expressions, variables, and constants—the fundamental building blocks of Swift. In this chapter, you’ll build the foundation for your future Swift programming career. You’ll get to grips with Swift’s type system, and learn the basics of using strings to represent text. Let’s get going...and you can see for yourself how swiftly you can write Swift code.
📄 Page
10
a. “Building from the blocks” b. “Basic operators” c. “Operating swiftly with mathematics” d. “Expressing yourself” e. “Names and types: peas in a pod” f. “Not all data is numbers” g. “Stringing things along with types” h. “String interpolation” 4. Chapter 3 You already know about expressions, operators, variables, constants, and types in Swift. It’s time to consolidate and build on that knowledge and explore some more advanced Swift data structures and operators: collections and control flow. In this chapter, we’re going to talk about putting collections of data into variables and constants, and how to structure data, manipulate data, and operate on data using control flow statements. We’ll be looking at other ways to collect and structure data later in the book, but for now let’s get started with arrays, sets, and dictionaries. a. “Sorting pizzas” b. “Swift collection types” c. “Collecting values in an array” d. “How big is that array, exactly? Is it empty?” e. “Collecting values in a set” f. “Collecting values in a dictionary” g. “Tuples”
📄 Page
11
h. “Everyone needs a good alias” i. “Control flow statements” j. “if statements” k. “switch statements” l. “Building a switch statement” m. “Range operators” n. “More complex switch statements” o. “Getting repetitive with loops” p. “Building a for loop” q. “Building a while loop” r. “Building a repeat-while loop” s. “Solving the pizza-sorting problem” t. “Phew, that’s a lot of Swift!” 5. Chapter 4 Functions in Swift allow you to package up a specific behavior or unit of work into a single block of code that you can call from other parts of your program. Functions can be standalone, or they can be defined as part of a class, a structure, or an enumeration, where they are usually referred to as methods. Functions let you break down complex tasks into smaller, more manageable, and more testable units. They’re a core part of the way you structure a program with Swift. a. “Functions in Swift let you reuse code” b. “Built-in functions” c. “What can we learn from built-in functions?”
📄 Page
12
d. “Improving the situation with a function” e. “Writing the body of the function” f. “Using functions” g. “Functions deal in values” h. “Many happy returns (from your functions)” i. “A variable number of parameters” j. “What can you pass to a function?” k. “Every function has a type” l. “Function types as parameter types” m. “Multiple return types” n. “Functions don’t have to stand alone” o. “Switching with enums” 6. Chapter 5 Functions are useful, but sometimes you need more flexibility. Swift allows you to use a function as a type, just like an integer or string. This means you can create a function and assign it to a variable. Once it’s assigned to a variable, you can call the function using the variable, or pass the function to other functions as a parameter. When you create and use a function in this manner, it’s called a closure. Closures are useful because they can capture references to constants and variables from the context in which they are defined. This is called closing over a value, hence the name. a. “Meet the humble closure” b. “Closures are better with parameters” c. “Boiling it all down to something useful”
📄 Page
13
d. “Reducing with closures” e. “Capturing values from the enclosing scope” f. “Escaping closures: the contrived example” g. “Autoclosures provide flexibility” h. “Shorthand argument names” 7. Chapter 6 Working with data often involves defining your own kinds of data. Structures—often shortened to their Swift language keyword, structs—allow you to create your own custom data types (just like String and Int are data types) by combining other types. Using structs to represent the data that your Swift code is working with allows you to step back and consider how the data that flows through your code fits together. Structs can hold variables and constants (which are called properties when they’re inside a struct) and functions (which are called methods). Let’s add some structure to your world, and dive into structs. a. “Let’s make a pizza, in all its glory...” b. “The initializer behaves just like a function” c. “Static properties make structures more flexible” d. “Methods inside structures” e. “Changing properties using methods” f. “Computed properties” g. “Getters and setters for computed properties” h. “Implementing a setter” i. “Swift Strings are actually structs” j. “The case for lazy properties”
📄 Page
14
k. “Using lazy properties” 8. Chapter 7 Structs showed us how useful it can be to build custom types. But Swift has a number of other tricks up its sleeve, including classes. Classes are similar to structs: they let you make new data types that have properties and methods within them. However, in addition to being reference types—instances of a specific class share a single copy of their data (unlike structs, which are value types and get copied)—classes support inheritance. Inheritance allows one class to build upon the features of another. a. “A struct by any other name (that name: a class)” b. “Inheritance and classes” c. “Replacing Overriding methods” d. “Final classes” e. “Automatic reference counting” f. “Mutability” 9. Chapter 8 You know all about classes and inheritance, but Swift has a few more tricks for structuring programs, and they’re a lot Swiftier. Meet protocols and extensions. Protocols in Swift let you define a blueprint specifying methods and properties that are required for some purpose, or some piece of functionality. A protocol is adopted by a class, structure, or enumeration, and the actual implementation happens there. Types that provide the functionality needed, and adopt a protocol, are referred to as conforming to that protocol. Extensions simply let you add new functionality to existing types. a. “The Robot Factory”
📄 Page
15
b. “Protocol inheritance” c. “Mutating methods” d. “Protocol types and collections” e. “Computed properties in extensions” f. “Extending a protocol” g. “Useful protocols and you” h. “Conforming to Swift’s protocols” 10. Chapter 9 Dealing with data that doesn’t exist can be challenging. Thankfully, Swift has a solution. Meet optionals. In Swift, an optional allows you to work with a value, or with the absence of a value. They’re one of the many ways that Swift is designed to be a safe language. You’ve occasionally seen optionals in your code so far, and now we’re going to explore them in more depth. Optionals make Swift safe because they keep you from accidentally writing code that would break if it’s missing data, or if something can sometimes return a value that isn’t actually a value. a. “Dealing with something that’s missing” b. “Why you might need an optional” c. “Optionals and handling missing data” d. “ Unwrapping optionals ” e. “ Unwrapping optionals with guard ” f. “Force unwrapping” g. “Generics” h. “A queue with generics”
📄 Page
16
i. “Here’s our new Queue type” 11. Chapter 10 It’s time to use your toolbox full of Swift techniques, features, and components: you’re going to start building user interfaces. A Swift UI, if you will. We’re going to bring everything together in this chapter to create our first true user interface. We’ll build a whole experience using SwiftUI, the user interface framework for Apple’s platforms. We’ll still be using Playgrounds, at least initially, but everything we’re doing here will lay the groundwork for an actual iOS application. Get ready: this chapter is full of code and a lot of new concepts. a. “What’s a UI framework, anyway?” b. “Your first SwiftUI UI” c. “UI building blocks” d. “Making a list, checking it…quite a few times, to get it perfect” e. “User interfaces with state” f. “Buttons are for pressing” g. “Let’s see how far you’ve come” h. “ Customizing your views with modifiers ” i. “Create a new SwiftUI Xcode project, for iOS” j. “Your Xcode will look something like this” k. “Create a new type to store a todo item in” l. “Make sure each todo item can be uniquely identified” m. “Create a user interface for the app”
📄 Page
17
n. “Implement a way to save the list of todos” o. “So, that’s a UI framework?” 12. Chapter 11 SwiftUI lets you do more than work with Buttons and Lists. You can also use shapes, animations, and more! In this chapter, we’re going to look at some of the more advanced ways you can construct a SwiftUI UI, and connect it to a data source that isn’t just user-generated content like todo items. SwiftUI lets you build responsive UIs that handle events coming from all sorts of places. We’ll be working with Xcode, Apple’s IDE, and we’ll be focusing on iOS apps, but everything you’ll learn is applicable to SwiftUI on iPadOS, macOS, watchOS, and tvOS as well. It’s time to explore the depths of SwiftUI! a. “What fancy things can be done with a UI framework?” b. “Create a new SwiftUI Xcode project, for iOS” c. “The Executive Timer UI and features” d. “Creating the basic elements of the app” e. “Pieces of the UI” f. “Setting up the UI of the Executive Timer” g. “Coding the pieces of the UI” h. “Combining the three elements” i. “The finishing touches” j. “Tabbed views for a clean UI” k. “2 Build a TabView containing your views” l. “Creating a new tabbed ContentView” m. “Creating the tabs and the TabView”
📄 Page
18
n. “Running your new tabbed Executive Timer” 13. Chapter 12 You’ve done lots of Swift. You’ve used Playgrounds and Xcode. We knew you’d have to say goodbye eventually, but the time has finally arrived. It’s hard to part, but we know you’ve got what it takes. In this chapter, our final chapter together (at least in this book), we’re going to do a final pass through many of the concepts you’ve learned, and build a handful of things together. We’ll make sure your Swift is shipshape, and give you some pointers on what to do next. Some homework, if you will. It’ll be fun, and we’ll part on a high note. a. “A journey must end...” b. “A recipe for a welcome screen” c. “Step by step assembly of the welcome screen” d. “Smash Share the state” e. “It’s time for our old friend...” f. “Building an app with multiple views that share state” g. “Building a two-view score tracker” h. “The ObservableObject” i. “The first view” j. “The second view” k. “The first view, again” l. “A fancy AsyncImage” m. “Meet Vapor, the Swift web framework” n. “Sending data over the web with Vapor”
📄 Page
19
how to use this book: Intro
📄 Page
20
NOTE In this section we answer the burning question: “So why DID they put that in a Swift book?”