41,99 €
Dive into the latest release of the Swift programming language with this advanced development book for building highly performant applications.
This book is for developers who want to delve into the newest version of Swift. If you are a developer who learns best by looking at and working with code, then this book is for you. A basic understanding of Apple's tools is beneficial but not mandatory.
Swift is the definitive language for Apple development today. It's a vital part of any iOS and macOS developer's skillset, helping them to build the most impressive and popular apps on the App Store—the sort of apps that are essential to iPhone and iPad users every day. With version 4.0, the Swift team has added new features to improve the development experience, making it easier to get the results you want and customers expect.
Inside, you'll find the key features of Swift 4.0 and quickly learn how to use the newest updates to your development advantage. From Objective-C interoperability and ARC to closures and concurrency, this advanced Swift guide will develop your expertise and help you become fluent in this vital programming language.
We'll give you an in-depth knowledge of some of the most sophisticated elements of Swift development, including protocol extensions, error-handling, design patterns, and concurrency. We'll guide you on how to use and apply them in your own projects. You'll see how to leverage the power of protocol-oriented programming to write flexible and easier-to-manage code.
A Step-by-step advanced guide
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 509
Veröffentlichungsjahr: 2017
BIRMINGHAM - MUMBAI
Copyright © 2017 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: June 2015
Second edition: November 2015
Third edition: October 2016
Fourth edition: September 2017
Production reference: 1250917
ISBN 978-1-78847-780-2
www.packtpub.com
Author
Jon Hoffman
Copy Editor
Safis Editing
Reviewer
Arthur Ariel Sabintsev
Project Coordinator
Ulhas Kambali
Commissioning Editor
Ashwin Nair
Proofreader
Safis Editing
Acquisition Editor
Reshma Raman
Indexer
Rekha Nair
ContentDevelopmentEditor
Vikas Tiwari
Graphics
Abhinash Sahu
Technical Editor
Subhalaxmi Nadar
Production Coordinator
Melwyn D'sa
Jon Hoffman has over 25 years of experience in the field of information technology. Over these years, Jon has worked in the areas of system administration, network administration, network security, application development, and architecture. Currently, Jon works as a senior software engineer for Syn-Tech Systems. Jon has developed extensively for the iOS platform since 2008. This includes several apps that he has published in the App Store, apps that he has written for third parties, and numerous enterprise applications. He has also developed mobile applications for the Android and Windows platforms. What really drives Jon is the challenges that the field of information technology provides, and there is nothing more exhilarating to him than overcoming a challenge. Some of Jon's other interests are spending time with his family, robotic projects, and 3D printing. Jon also really enjoys Tae Kwon Do, where he and his oldest daughter, Kailey, earned their black belts together early in 2014, Kim (his wife), earned her black belt in December 2014, and his youngest daughter, Kara, is currently working toward her black belt.
Arthur Ariel Sabintsev is one of the lead iOS engineers at The Washington Post. His mobile engineering career includes working for a U.S. government-funded digital identity startup (ID.me), a Techstars-funded video startup (Shelby.tv), and an award winning mobile development agency (Fueled). He's spent the last 4 years teaching Swift and Objective-C for General Assembly and Betamore. He also maintains over a dozen open source iOS libraries and has made contributions to the Swift language and to the Swift Source Compatibility Suite. Before leaving his PhD program, he was an experimental nuclear physicist who worked underground colliding subatomic and subnuclear particles.
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review.
If you'd like to join our team of regular reviewers, you can email us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
Taking the First Steps with Swift
What is Swift?
Swift features
Playgrounds
Getting started with Playgrounds
iOS, tvOS, and macOS Playgrounds
Showing images in a Playground
Creating and displaying graphs in Playgrounds
What Playgrounds are not
Swift language syntax
Comments
Semicolons
Parentheses
Curly brackets
An assignment operator does not return a value
Spaces are optional in conditional and assignment statements
Hello World
Summary
Learning about Variables, Constants, Strings, and Operators
Constants and variables
Defining constants and variables
Type safety
Type inference
Explicit types
Numeric types
Integer types
Floating-point and Double values
The Boolean type
The string type
Optional variables
Optional binding
Optional chaining
Enumerations
Operators
The assignment operator
Comparison operators
Arithmetic operators
The remainder operator
Compound assignment operators
The ternary conditional operator
The logical NOT operator
The logical AND operator
The logical OR operator
Summary
Using Swift Collections and the Tuple Type
Swift collection types
Mutability
Arrays
Creating and initializing arrays
Accessing the array elements
Counting the elements of an array
Is the array empty?
Appending to an array
Inserting a value into an array
Replacing elements in an array
Removing elements from an array
Merging two arrays
Retrieving a subarray from an array
Making bulk changes to an array
Algorithms for arrays
Sort
Sorted
Filter
Map
forEach
Iterating over an array
Dictionaries
Creating and initializing dictionaries
Accessing dictionary values
Counting the key or values in a dictionary
Is the dictionary empty?
Updating the value of a key
Adding a key-value pair
Removing a key-value pair
Set
Initializing a set
Inserting items into a set
Determining the number of items in a set
Checking whether a set contains an item
Iterating over a set
Removing items in a set
Set operations
Tuples
Summary
Control Flow and Functions
What have we learned so far?
Curly brackets
Parentheses
Control flow
Conditional statements
The if statement
Conditional code execution with the if...else statement
The guard statement
The for-in loop
Using the for...in loop
The while loop
Using the while loop
Using the repeat-while loop
The switch statement
Using case and where statements with conditional statements
Filtering with the where statement
Filtering with the for-case statement
Using the if-case statement
Control transfer statements
The continue statement
The break statement
The fallthrough statement
Functions
Using a single parameter function
Using a multi-parameter function
Defining a parameter's default values
Returning multiple values from a function
Returning optional values
Adding external parameter names
Using variadic parameters
Inout parameters
Putting it all together
Summary
Classes and Structures
What are classes and structures?
Similarities between classes and structures
Differences between classes and structures
Value versus reference types
Creating a class or structure
Properties
Stored properties
Computed properties
Property observers
Methods
Custom initializers
Internal and external parameter names
Failable initializers
Access controls
Inheritance
Overriding methods and properties
Overriding methods
Overriding properties
Preventing overrides
Protocols
Protocol syntax
Property requirements
Method requirements
Extensions
Memory management
How ARC works
Strong reference cycles
Summary
Using Protocols and Protocol Extensions
Protocols as types
Polymorphism with protocols
Type casting with protocols
Protocol extensions
Do I need to use protocols?
Swift's standard library
Summary
Protocol-Oriented Design
Requirements
Object-oriented design
Protocol-oriented design
Protocol inheritance
Protocol composition
Protocol-oriented design
Using the where statement with protocols
Structures versus classes
The array structure
Summary
Writing Safer Code with Availability and Error Handling
Native error handling
Representing errors
Throwing errors
Catching errors
The availability attribute
Summary
Custom Subscripting
Introducing subscripts
Subscripts with Swift arrays
Creating and using custom subscripts
Read-only custom subscripts
Calculated subscripts
Subscript values
External names for subscripts
Multidimensional subscripts
When not to use a custom subscript
Summary
Using Optional Types
Introducing optionals
The need for optional types in Swift
Defining an optional
Using optionals
Forced unwrapping of an optional
Optional binding
Returning optionals from functions and methods
Using an optional as a parameter in a function or method
Optional binding with the guard statement
Optional types with tuples
Optional chaining
The nil coalescing operator
Summary
Working with Generics
An introduction to generics
Generic functions
Generic types
Generic subscripts
Associated types
Summary
Working with Closures
An introduction to closures
Simple closures
Shorthand syntax for closures
Using closures with Swift's array algorithms
Standalone closures and good style guidelines
Changing functionality
Selecting a closure based on results
Creating strong reference cycles with closures
Summary
Using Mix and Match
What is mix and match?
When to use mix and match
Using Swift and Objective-C together in the same project
Creating the project
Adding Swift files to the Objective-C project
The Objective-C bridging header file - part 1
Adding the Objective-C file to the project
The Messages Objective-C class
The Objective-C bridging header file - part 2
The MessageBuilder Swift class - accessing Objective-C code from Swift
The Objective-C class - accessing Swift code from Objective-C
Summary
Concurrency and Parallelism in Swift
Concurrency and parallelism
Grand Central Dispatch
Calculation type
Creating queues
Creating and using a concurrent queue
Creating and using a serial queue
async versus sync
Executing code on the main queue function
Using asyncAfter
Using the Operation and OperationQueue types
Using BlockOperation
Using the addOperation() method of the operation queue
Subclassing the Operation class
Summary
Swift Formatting and Style Guide
What is a programming style guide?
Your style guide
Do not use semicolons at the end of statements
Do not use parentheses for conditional statements
Naming
Custom types
Functions and methods
Constants and variables
Indenting
Comments
Using the self keyword
Constants and variables
Optional types
Using optional binding
Using optional chaining instead of optional binding for multiple unwrapping
Using type inference
Using shorthand declaration for collections
Using switch rather than multiple if statements
Don't leave commented-out code in your application
Summary
Swift Core Libraries
Apple's URL loading system
URLSession
URLSessionConfiguration
URLSessionTask
URL
URLRequest
HTTPURLResponse
REST web services
Making an HTTP GET Request
Making an HTTP POST request
Formatter
DateFormatter
NumberFormatter
FileManager
Encoding and Decoding JSON Data
Using JSONEncoder
Using JSONDecoder
Summary
Adopting Design Patterns in Swift
What are design patterns?
Creational patterns
The singleton design pattern
Understanding the problem
Understanding the solution
Implementing the singleton pattern
The builder design pattern
Understanding the problem
Understanding the solution
Implementing the builder pattern
Structural design patterns
The bridge pattern
Understanding the problem
Understanding the solution
Implementing the bridge pattern
The façade pattern
Understanding the problem
Understanding the solution
Implementing the façade pattern
The proxy design pattern
Understanding the problem
Understanding the solution
Implementing the proxy pattern
Behavioral design patterns
The command design pattern
Understanding the problem
Understanding the solution
Implementing the command pattern
The strategy pattern
Understanding the problem
Understanding the solution
Implementing the strategy pattern
Summary
Swift is a programming language that was first introduced by Apple at the World Wide Developers Conference (WWDC) in 2014. Each year since that initial announcement, Apple has announced a new version of Swift. At the WWDC in 2017, Apple announced Swift 4.
Swift 4 offers some exciting changes, such as Strings, which are once again a collection of Generic subscripts and one-side range operators. In this book, we will look at these and other changes in Swift.
Chapter 1, Taking the First Steps with Swift, introduces you to the the Swift programming language and discusses what inspired Apple to create Swift. We'll also go over the basic syntax of Swift and how to use Playgrounds to experiment and test the Swift code.
Chapter 2, Learning about Variables, Constants, Strings, and Operators, introduces you to variables and constants in Swift and when to use them. We will also look at the most common operators in the Swift language.
Chapter 3, Using Swift Collections and the Tuple Type, explains Swift's array, set, and dictionary collection types and shows examples of how to use them. We'll also show how to use the Tuple type in Swift.
Chapter 4, Control Flow and Functions, shows you how to use Swift's control flow statements. These include loops, conditional, and control transfer statements. The second half of the chapter is all about functions.
Chapter 5, Classes and Structures, dedicates itself to Swift's classes and structures. We'll look at what makes them similar and what makes them different. We'll also look at access controls. We will conclude this chapter by looking at memory management in Swift, so you will understand how ARC works and how to avoid strong reference cycles.
Chapter 6, Using Protocols and Protocol Extensions, covers both protocols and protocol extensions in detail because protocols are very important to the Swift language, and having a solid understanding of them will help us write flexible and reusable code.
Chapter 7, Protocol-Oriented Design, covers the best practices of protocol-oriented design with Swift. This will be a brief overview of what is covered in the protocol-oriented programming book.
Chapter 8, Writing Safer Code with Availability and Error Handling, covers error handling in depth as well as the new availability feature. This feature is really important for writing safe code.
Chapter 9, Custom Subscripting, discusses how we can use custom subscripts in our classes, structures, and enumerations.
Chapter 10, Using Optional Types, explains what optional types really are and what are the various ways to unwrap them. For a developer who is just learning Swift, optional types can be one of the most confusing items to learn.
Chapter 11, Working with Generics, explains how Swift implements generics. Generics are a very important part of the Swift language and it is essential to understand them.
Chapter 12, Working with Closures, teaches you how to define and use closures in our code. Closures in Swift are similar to blocks in Objective-C except that they have a much cleaner and easier way of using syntax.
Chapter 13, Using Mix and Match, explains mix and match and demonstrates how you can include Swift code in your Objective-C projects and Objective-C code in your Swift projects.
Chapter 14, Concurrency and Parallelism in Swift, shows you how to use both grand central dispatch and operation queues to add concurrency and parallelism to your applications. Understanding and knowing how to add concurrency and parallelism to your apps can significantly enhance the user experience.
Chapter 15, Swift Formatting and Style Guide, defines a style guide for the Swift language that can be used as a template for enterprise developers who need to create a style guide.
Chapter 16, Swift Core Libraries, explores some of the functionality in the Swift core library. This will include accessing REST services working with JSON data and the formatting framework.
Chapter 17, Adopting Design Patterns in Swift, shows you how to implement some of the more common design patterns in Swift. A design pattern identifies a common software development problem and provides a strategy for dealing with it.
To follow along with the examples in this book, you'll need to have an Apple computer with OS X 10.13 or higher installed. You'll also need to install Xcode version 9.0 or higher with Swift version 4 or higher.
This book is for developers who want to dive into the newest version of Swift. If you are a developer who learns best by looking at and working with code, then this book is for you. A basic understanding of Apple's tools is beneficial, but not mandatory.
Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply email [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files emailed directly to you. You can download the code files by following these steps:
Log in or register to our website using your email address and password.
Hover the mouse pointer on the
SUPPORT
tab at the top.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on
Code Download
.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Mastering-Swift-4-Fourth-Edition. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from http://www.packtpub.com/sites/default/files/downloads/MasteringSwift4FourthEdition_ColorImages.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title. To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at [email protected] with a link to the suspected pirated material. We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
Ever since I was 12 years old and wrote my first program in the BASIC programming language, programming has been a passion for me. Even as I became a professional programmer, programming remained more of a passion than a job, but in the years preceding the first release of Swift, that passion had waned. I was unsure why I was losing that passion. I attempted to recapture that passion with some of my side projects, but nothing really brought back the excitement that I used to have. Then Apple announced Swift in 2014. Swift is such an exciting and progressive language that it has brought a lot of that passion back and made programming fun again. Now that official versions of Swift are available for the Linux platform, and un-official versions for Windows and the ARM platform, learning and using Swift is becoming available to people outside the Apple ecosystem. This is really an exciting time to be learning the Swift language.
In this chapter, you will learn:
What is Swift?
What are some of the features of Swift?
What are Playgrounds?
How to use Playgrounds?
What the basic syntaxes of the Swift language are?
Swift is a programming language that was introduced, by Apple, at the World Wide Developers Conference (WWDC) in 2014. Swift was arguably the most significant announcement at WWDC 2014 and very few people, including Apple insiders, were aware of the project's existence prior to it being announced.
It was amazing, even by Apple's standards, that they could keep Swift a secret for as long as they did and that no one suspected they were going to announce a new development language. At WWDC 2015, Apple made another big splash when they announced Swift 2. Swift 2 was a major enhancement to the Swift language. During that conference, Chris Lattner said that a lot of the enhancements were based on direct feedback that Apple received from the development community. It was also announced that Swift would become an open source project. In my opinion, this was the most exciting announcement of the WWDC 2015.
In December of 2015, Apple officially released Swift as open source with the https://swift.org/ site dedicated to the open source Swift community. The Swift repository is located on Apple's GitHub page (http://github.com/apple). The Swift evolution repository (https://github.com/apple/swift-evolution) tracks the evolution of Swift by documenting the proposed changes. A list of which proposals were accepted and which were rejected can be found in the evolution repository.
Swift 3, which was released in 2016, was a major enhancement to the Swift language that was not source-compatible with previous releases of the Swift language. It contained fundamental changes to the language itself and to the Swift standard library. One of the main goals of Swift 3 was to be source-compatible across all platforms so the code that was written for one platform would be compatible with all other platforms. This means that the code we develop for macOS should work on Linux.
Now, Apple has released Swift 4. One of the primary goals of the Swift 4 compiler is to be source-compatible with Swift 3. This will allow us to compile both Swift 3 and Swift 4 projects with the Swift 4 compiler. Apple has established a community-owned source compatibility test suite that will be used to regression-test changes to the compiler. Projects that are added to the test suite will be periodically built against the latest development version of Swift to help understand the impact of the changes being made to Swift. You can find the Swift source compatibility page here: https://swift.org/source-compatibility/.
One of the original goals of Swift 4 was to stabilize the Swift ABI (Application Binary Interface). The main benefit of a stable ABI is to allow us to distribute frameworks in a binary format across multiple versions of Swift. If a stable ABI were in place, we would be able to build a framework with the Swift 4 compiler and have it work with applications that were written in future versions of Swift. This feature ended up being deferred for now. Hopefully, Apple will be able to stabilize the ABI in future versions of Swift.
The development of Swift was started in 2010 by Chris Lattner. He implemented much of the basic language structure with only a few people being aware of its existence. It wasn't until late 2011 that other developers began to contribute to Swift. In July of 2013, it became a major focus of the Apple Developer Tools group.
Chris started working at Apple in the summer of 2005. He has held several positions in the Developer Tools group, and was the director and architect of that group when he left Apple in 2017. On his home page (http://www.nondot.org/sabre/), he notes that Xcode's Playground (read more on Playgrounds a little later in this chapter) became a personal passion of his because it makes programming more interactive and approachable. If you are using Swift on the Apple platform, you will be using Playgrounds a lot as a test and experimentation platform. You can also use Swift Playgrounds on the iPad.
There are a lot of similarities between Swift and Objective-C. Swift adopts the readability of Objective-C's named parameters and dynamic object model. When we refer to Swift as having a dynamic object model, we are referring to the ability for types to change at runtime. This includes adding new (custom) types and changing/extending the existing types.
While there are a lot of similarities between Swift and Objective-C, there are significant differences between them as well. Swift's syntax and formatting are a lot closer to Python than Objective-C, but Apple did keep the curly braces. I know Python people would disagree with me, and that is all right because we all have different opinions, but I like the curly braces. Swift actually makes the curly braces required for control statements, such as if and while, which eliminates bugs, such as the goto fail, in Apple's SSL library.
When Apple first introduced Swift, it said that Swift is Objective-C without the C. This really only tells us half of the story. Objective-C is a superset of C and provides object-oriented capabilities and a dynamic runtime to the C language. This meant that with Objective-C, Apple needed to maintain compatibility with C, which limited the enhancements it could make to the Objective-C language. As an example, Apple could not change how the switch statement functioned and has still maintained compatibility with the C language.
Since Swift does not need to maintain the same C compatibility as Objective-C, Apple was free to add any feature/enhancement to the language. This allowed Apple to include the best features from many of today's most popular and modern languages, such as Objective-C, Python, Java, Ruby, C#, Haskell, and many others.
The following chart shows a list of some of the most exciting enhancements that Swift offers as compared to the Objective-C language:
Swift feature
Description
Type inference
Swift can automatically deduce the type of a variable or constant, based on the initial value.
Generics
Generics allow us to write code only once to perform identical tasks for different types of object.
Collection mutability
Swift does not have separate objects for mutable or non-mutable containers. Instead, you define mutability by defining the container as a constant or variable.
Closure syntax
Closures are self-contained blocks of functionality that can be passed around and used in our code.
Optionals
Optionals define a variable that might not have a value.
Switch statement
The Switch statement has been drastically improved. This is one of my favorite improvements.
Tuples
Functions can have multiple return types using tuples.
Operator overloading
Classes can provide their own implementation of existing operators.
Enumerations with associated values
In Swift, we can do a lot more than just define a group of related values with enumerations.
Protocols and Protocol-oriented Design
Apple introduced the Protocol-oriented Programming paradigm with Swift version 2. This is a new way of not only writing applications but also changes how we think about programming.
There is one feature that I did not mention in the preceding chart because it is technically not a feature of Swift; it is a feature of Xcode and the compiler. This is also a feature that is specific to the Apple platform with Xcode. This feature is Mix and Match, which allows us to create applications that contain both Objective-C and Swift files. This allows us to systematically update our existing Objective-C applications with Swift classes and use Objective-C libraries/frameworks in our Swift applications.
Before we begin our journey into the wonderful world of Swift development, let's take a detour and visit a place that I have loved ever since I was a kid: the Playground.
When I was a kid, the best part of the school day was going to the playground. It really did not matter what we were playing as long as we were on the playground. When Apple introduced Playgrounds as part of Xcode 6, I was excited just by the name, but I wondered if Apple would be able to make its Playground as fun as the playgrounds of my youth. While Apple's Playgrounds might not be as fun as playing kickball when I was 9-years old, it definitely brings a lot of fun back to experimenting and playing with code.
Playgrounds are interactive work environments that let us write code and see the results immediately as changes are made to the code. This means that Playgrounds are a great way to learn and experiment with Swift. Now that we can use Swift Playgrounds on the iPad, we do not even need to have a computer in front of us to experiment with Swift.
Playgrounds also make it incredibly easy to try out new APIs, prototype new algorithms, and demonstrate how code works. We will be using Playgrounds throughout this book to show how our sample code works. Therefore, before we really get into Swift development, let's spend some time learning about, and getting comfortable with, Playgrounds.
Do not worry if the Swift code does not make a lot of sense right now; as we proceed through the book, the code we use in the following examples will begin to make sense. We are simply trying to get a feel for Playgrounds right now.
A Playground can have several sections, but the three that we will be using extensively in this book are:
Coding Area
: This is where you enter your Swift code.
Results Sidebar
: This is where the results of your code are shown. Each time you type in a new line of code, the results are re-evaluated and the results sidebar is updated with the new results.
Debug Area
: This area displays the output of the code, and it can be very useful for debugging.
The following screenshot shows how the sections are arranged in a Playground:
Let's start a new Playground. The first thing we need to do is to start Xcode. Once Xcode has started, we can select the Get started with a playground option, as shown in the following screenshot:
Alternatively, we can navigate to the Playground by going to File | New from the top menu bar, as shown in the following screenshot:
Next, we should see a screen similar to the following screenshot. This screen lets us name our Playground and select whether the Playground is an iOS, tvOS, or macOS Playground. For most of the examples in this chapter, it is safe to assume that you can select any of the OS options unless it is otherwise noted. You can also select a template to use. For the examples in this book, we will be using the Blank template for all of our code:
Finally, we are asked for the location in which to save our Playground. After we select the location, the Playground will open and look similar to the following screenshot:
In the preceding screenshot, we can see that the coding area of the Playground looks similar to the coding area for an Xcode project. What is different here is the sidebar on the right-hand side. This sidebar is where the results of our code are shown. The code in the previous screenshot imports the Cocoa framework since it is a macOS playground. If it was an iOS playground it would import the UIKit framework instead.
If your new Playground does not open the debug area, you can open it manually by pressing the shift + command + Y keys together. You can also close the debug area by pressing shift + command + Y again. Later in the chapter, we will see why the debug area is so useful. Another way to open or close the debug area is to click on the button that looks like an upside-down triangle in a box that is in the border between the debug area and the coding area.
When you start a new iOS or tvOS Playground, the Playground imports the UIKit framework. This gives us access to the UIKit framework that provides the core infrastructure for iOS and tvOS applications. When we start a new macOS Playground, the Playground imports the Cocoa framework.
What the last paragraph means is that, if we want to experiment with specific features of either UIKit or Cocoa, we will need to open the correct Playground. As an example, if we have an iOS Playground open and we want to create an object that represents a color, we would use a UIColor object. If we had a macOS playground open, we would use an NSColor object to represent a color.
Playgrounds are great at showing the results of code as text in the results sidebar; however; they can also do a lot more than just work with text. We can display other items such as images and graphs. Let's look at how we would show an image in a Playground. The first thing we need to do is to load the image into the resource directory of our Playground.
The following steps show how to load an image into the resource directory:
Let's begin by showing the project navigator sidebar. To do this, in the top menu bar, navigate to
View
|
Navigators
|
Show Project Navigator
or use the
command
+
1
keyboard shortcut. The project navigator looks similar to this:
Once we have the
Project Navigator
open, we can drag the image into the
Resources
folder so that we can access it from our code. Once we drag the image file over it and drop it, it will appear in the
Resources
folder, as shown here:
Now, we can access the image that is in our
Resources
folder within our code. The following screenshot shows how we would do this. At this time, the code used to access the image is not as important as knowing how to access resources within a Playground:
To view the image, we need to hover our cursor in the results sidebar over the section that shows the width and height of the image. In our example, the width and height section shows
w 256 h 256
. Once we hover the mouse pointer over the width and height, we should see two symbols, as shown in the following screenshot:
We can press either of the symbols to show the image. The one that looks like a box within a box will display the image within the playground's code section, while the one that looks like an eye will pop the image up outside the playground. The following screenshot shows what it looks like if we display the image within the playground:
Having the ability to create and display graphs can be very useful when we want to see the progression of our code. Let's look at how we can create and display graphs in a playground.
Creating and displaying graphs is really useful when we are prototyping new algorithms because it allows us to see the value of a variable throughout the course of the calculations. To see how graphing works, look at the following Playground:
In this Playground, we set the variable j to 1. Next, we create a for loop that assigns numbers 1 through 5 to the variable i. At each step in the for loop, we set the value of the variable j to the current value of j multiplied by i. The graph shows the values of the variable j at each step of the for loop. We will be covering for loops in detail later in this book.
To bring up the graph, click on the symbol that is shaped like a circle with a dot in it. We can then move the timeline slider to see the values of variable j at each step of the for loop. The following Playground shows what the graph should look like:
There is a lot more that we can do with Playgrounds, and we have only scratched the surface in our quick introduction here. Before we leave this brief introduction, let's take a look at what Playgrounds are not so that we can better understand when not to use Playgrounds:
Playgrounds should not be used for performance testing: The performance you see from any code that is run in a Playground is not representative of how fast the code will run when it is in your project.
Playgrounds do not support on-device execution. You cannot run the code that is present in a Playground as an external application or on an external device.
If you are an Objective-C developer, and you are not familiar with modern languages such as Python or Ruby, the code in the previous screenshots may have looked pretty strange. The Swift language syntax is a huge departure from Objective-C, which was based largely on Smalltalk and C.
The Swift language uses modern concepts and syntax to create very concise and readable code. There is also a heavy emphasis on eliminating common programming mistakes. Before we get into the Swift language itself, let's look at some of the basic syntax of the Swift language.
Writing comments in Swift code is a little different from writing comments in Objective-C code. We can still use the double slash // for single-line comments and the /* and */ for multiline comments; however, if we want to use the comments to also document our code, we need to use the triple slash ///.
To document our code we generally use fields that Xcode recognizes. These fields are:
Parameter
: When we start a line with
- parameter {param name}:
Xcode recognizes this as the description of a parameter
Return
: When we start a line with
- return:
Xcode recognizes this as the description of the return value
Throws
: When we start a line with
- throws:
Xcode recognizes this as the description of any errors that this method may throw
The following Playground shows examples of both single-line and multiline comments and how to use the comment fields:
To write good comments, I would recommend using single-line comments within a function to give quick one-line explanations of your code. We then use multiline comments outside functions and classes to explain what the function and class do. The preceding Playground shows a good way to use comments. By using proper documentation, as we did in the preceding screenshot, we can use the documentation feature within Xcode. If we hold down the option key and then click on the function name anywhere in our code, Xcode will display a pop-up with the description of the function.
This next screenshot shows what that pop-up would look like:
We can see that the documentation contains six fields. These fields are:
Declaration
: This is the function's declaration
Description
: This is the description of the function as it appears in the comments
Parameters
: The parameter descriptions are prefixed with the
Parameters:
tag in the comment section
Throws
: The throws description is prefixed with the
throws
: tag and describes what errors are thrown by the methods
Returns
: The return description is prefixed with the
returns:
tag in the comment section
Declared In
: This is the file that the function is declared in so that we can easily find it
There are significantly more fields that we can add to our comments. You can find the complete list on Apple's site here:
https://developer.apple.com/library/content/documentation/Xcode/Reference/xcode_markup_formatting_ref/MarkupFunctionality.html
You may have noticed, from the code samples so far, that we are not using semicolons at the end of lines. The semicolons are optional in Swift; therefore, both lines in the following Playground are valid in Swift:
For style purposes, it is strongly recommended that you do not use semicolons in your Swift code. If you are really set on using semicolons, then be consistent and use them on every line of code; however, there is no warning if you forget them. I will stress again, that it is recommended that you do not use semicolons in Swift.
In Swift, parentheses around conditional statements are optional; for example, both if statements in the following Playground are valid:
For style purposes, it is recommended that you do not include parentheses in your code unless you have multiple conditional statements on the same line. For readability purposes, it is good practice to put parentheses around the individual conditional statements that are on the same line.
In Swift, unlike most other languages, the curly bracket is required after conditional or loop statements. This is one of the safety features that are built into Swift. Arguably, there have been numerous security bugs that may have been prevented if the developer would have used curly braces. These bugs could also have been prevented by other means such as unit testing and code reviews, but requiring developers to use curly braces, in my opinion, is a good security standard.
The following Playground shows you the error you get if you forget to include curly braces:
For both conditional (if and while) and assignment () statements, the white spaces are optional. Therefore, in the following Playground, both the i block and the j block of code are valid:
For style purposes, I would recommend adding the white spaces as the j block shows (for readability purposes) but, as long as you pick one style and are consistent, either style should be acceptable.
We began this chapter with a discussion on the Swift language and gave a brief history about the language. We also mentioned some of the changes that will be present in Swift 4 and noted that ABI stabilization will be pushed out to a future version of Swift. We then showed how to start and use Playgrounds to experiment with Swift programming. We also covered the basic Swift language syntax and discussed proper language styles. The chapter concluded with two Hello World examples.
In the next chapter, we will see how to use variables and constants in Swift. We will also look at the various data types and how to use operators in Swift.
The first program I ever wrote was written in the BASIC programming language and was the typical Hello World application. This application was exciting at first, but the excitement of printing static text wore off pretty quickly. For my second application, I used BASIC's input command to prompt the user for a name and then printed out a custom hello message to the user with their name in it. At the age of 12, it was pretty cool to display Hello Han Solo. This application led me to create numerous Mad Lib-style applications that prompted the user for various words and then put those words into a story that was displayed after the user had entered all the required words. These applications introduced me to, and taught me, the importance of variables. Every useful application I've created since then has used variables.
In this chapter, we will cover the following topics:
What are variables and constants?
What is the difference between explicit and inferred typing?
What are numeric, string, and Boolean types?
Defining what Optional types are?
Explaining how enumerations work in Swift?
Explaining how Swift's operators work?
Constants and variables associate an identifier (such as myName or currentTemperature) with a value of a particular type (such as the String or Int type), where the identifier can be used to retrieve the value. The difference between a constant and a variable is that a variable can be updated or changed, while a constant cannot be changed once a value is assigned to it.
Constants are good for defining values that you know will never change, like the temperature that water freezes at or the speed of light. Constants are also good for defining a value that we use many times throughout our application, such as a standard font size or the maximum number of characters in a buffer. There will be numerous examples of constants throughout this book, and it is recommended that we use constants rather than variables whenever possible.
Variables tend to be more common in software development than constants. This is mainly because developers tend to prefer variables over constants. In Swift, we receive a warning if we declare a variable that is never changed. We can make useful applications without using constants (although it is a good practice to use them); however, it is almost impossible to create a useful application without variables.
You can use almost any character in the naming/identifier of a variable or constant (even Unicode characters); however, there are a few rules that you must follow:
An identifier must not contain any whitespace.
It must not contain any mathematical symbols or arrows.
An identifier must not contain private-use or invalid Unicode characters.
It must not contain line- or box-drawing characters.
It must not start with a number, but it can contain numbers.
If you use a Swift keyword as an identifier, surround it with back ticks; using a Swift keyword as an identifier is strongly discouraged.
Swift is a type-safe language, which means we are required to define the types of the values we are going to store in a variable. We will get an error if we attempt to assign a value to a variable that is of the wrong type. The following Playground shows what happens if we attempt to put a string value into a variable that expects integer values.
Swift performs a type check when it compiles code, therefore, it will flag any mis-matched types with an error. The error message in this Playground explains quite clearly that we are trying to insert a string value into an integer variable.
How does Swift know that the constant integerVar is of the Int type? Swift uses type inference to figure out the appropriate type. Let's look at what type inference is.
