Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Mastering Swift 5
Mastering Swift 5

Mastering Swift 5: Deep dive into the latest edition of the Swift programming language , Fifth Edition

eBook
$17.99 $26.99
Paperback
$38.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Mastering Swift 5

Taking the First Steps with Swift

Ever since I was 12 years old and wrote my first program in the BASIC programming language, I have been passionate about programming. 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 it with some of my side projects, but nothing really brought back the excitement that I used to have. Then, something amazing happened: 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. With official versions of Swift available for the Linux platform, and unofficial 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 about the following topics:

  • What is Swift?
  • What are some of the features of Swift? What are playgrounds?
  • How to use playgrounds
  • What are the basic syntaxes of the Swift language?

What is Swift?

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 WWDC 2015.

In December 2015, Apple officially released Swift as open-source with the https://swift.org/ site, which is 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. In addition to these resources, Apple has moved away from using mailing lists as the primary form of communication with the Swift community, and has set up Swift forums (https://forums.swift.org).

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.

In September 2017, Swift 4 was released. 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 Application Binary Interface (ABI). 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 is 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 to Swift 5.

Now that Apple has released Swift 5, the ABI has been declared stable for all Apple platforms. You can read Swift's ABI Stability Manifesto here: https://github.com/apple/swift/blob/master/docs/ABIStabilityManifesto.md. As development for Swift on other platforms, such as Linux, matures, the Swift Core team has said that they will evaluate stabilizing the ABI for those platforms as well. A stable ABI means that a library that is compiled for one version of Swift, let's say Swift 5, will theoretically work with future versions of Swift without having to be recompiled.

The last version of the Mastering Swift series was released when Swift 4.0 was released. Since that time, there have been numerous enhancements to the Swift language with two major versions, Swift 4.2 and Swift 5, being released. Throughout this book, we will see how to use a number of these enhancements.

The development of Swift was started in 2010 by Chris Lattner. He implemented much of the basic language structure when only a few people were aware of its existence. It wasn't until late 2011 that other developers began to contribute to Swift. In July 2013, it became a major focus of the Apple Developer Tools group.

Chris started working at Apple in the summer of 2005. He held several positions within 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 (we'll talk more about 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 brackets. I know Python people would disagree with me, and that is all right because we all have different opinions, but I like the curly brackets. Swift actually requires the curly brackets for control statements, such as if and while, which eliminates bugs, such as the goto fail in Apple's SSL library.

Swift features

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#, and Haskell.

The following chart shows a list of some of the most exciting enhancements that Swift offers 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 changing how we think about programming.

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.

Playgrounds

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 whether Apple would be able to make its playgrounds as fun as the playgrounds of my youth. While Apple's playgrounds might not be as fun as playing kickball when I was nine years old, it definitely brings a lot of fun back to experimenting and playing with code.

Playgrounds are also available for the iPad. While we are not going to cover the iPad version specifically in this section, the iPad version is a great way to experiment with the Swift language and is a great way to get children interested in programming.

Getting started with playgrounds

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.

If you are using Swift on the Linux platform, you will not have playgrounds available, but you can use the Read-Evaluate-Print-Loop (REPL) shell to experiment with Swift without compiling your code. If you are using Swift on something other than a macOS computer or the iPad, you can safely skip this section.

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 this book, the code that 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 the following:

  • 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 these sections are arranged in a playground:

Let's start a new playground. The first thing we need to do is 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 were 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 this 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 on the border between the debug area and the coding area.

iOS, tvOS, and macOS playgrounds

When you start a new iOS or tvOS playground, the playground imports the UIKit framework. This gives us access to the UIKit framework, which 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.

Showing images in a playground

It is very easy to receive the results of our code as text within the results sidebar of a playground; 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:

  1. Show 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:
  1. In the Project Navigator, 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:
  1. Let's 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 that was used to access the image is not as important as knowing how to access resources within a playground:
  1. 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 next to the width and height. One looks like an eye and the other is a box. The following screenshot shows these:
  1. 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 in playgrounds

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 our calculations. To see how graphing works, look at the following playground:

In this playground, we set the j variable to 1. Next, we create a for loop that assigns numbers 1 through 5 to the i variable. At each step in the for loop, we set the value of the j variable to the current value of j multiplied by i. The graph shows the values of the j variable 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 the j variable at each step of the for loop. The following playground shows what the graph should look like:

What playgrounds are not

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

Swift language syntax

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.

Comments

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 (///) or multiline comment block.

Xcode will also auto-generate a comment template based on your signature of the method/function by highlighting it and pushing command + option+ / together.

To document our code, we generally use fields that Xcode recognizes. These fields are as follows:

  • 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 popup with the description of the function.

The following screenshot shows what that popup would look like:

We can see that the documentation contains five fields. These fields are as follows:

  • 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: https://developer.apple.com/library/content/documentation/Xcode/Reference/xcode_markup_formatting_ref/MarkupFunctionality.html.

If you are developing for the Linux platform, I would still recommend using Apple's documentation guidelines because, as other Swift IDEs are developed, I believe they will support the same guidelines.

Semicolons

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, be consistent and use them on every line of code; however, there is no warning if you forget them.

I will stress this again: it is recommended that you do not use semicolons in Swift.

Parentheses

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.

Curly brackets

In Swift, unlike most other languages, the curly bracket is required after conditional or loop statements. This is one of the safety features that is built into Swift. Arguably, there have been numerous security bugs that may have been prevented if the developer had used curly brackets. These bugs could have also been prevented by other means, such as unit testing and code reviews, but requiring developers to use curly brackets, in my opinion, is a good security standard.

The following playground shows you the error you get if you forget to include curly brackets:

An assignment operator does not return a value

In most other languages, the following line of code is valid, but it probably isn't what the developer meant to do:

if (x = 1) {} 

In Swift, this statement is not valid. Using an assignment operator (=) in a conditional statement (if, while, and guard) will throw an error. This is another safety feature built into Swift. It prevents the developer from forgetting the second equals sign (=) in a comparison statement. This error is shown in the following playground:

Spaces are optional in conditional and assignment statements

For both conditional (if and while) and assignment (=) statements, the white spaces are optional. Therefore, in the following playground, both the i and the j blocks of code are valid:

For style purposes, I recommend adding the white spaces as the j block shows (for readability) but, as long as you pick one style and are consistent, either style is acceptable.

Hello World

All good computer books that are written to teach a computer language have a section that shows the user how to write a Hello World application. This book is no exception. In this section, we will show you how to write two different Hello World applications.

Our first Hello World application will be a traditional Hello World application that simply prints Hello World to the console. Let's begin by creating a new playground and naming it Chapter_1_Hello_World.

In Swift, to print a message to the console, we use the print() function. In its most basic form, we would use the print function to print out a single message, as shown in the following code:

print("Hello World") 

Usually, when we use the print() function, we want to print more than just static text. We can include the value of variables and/or constants by using string interpolation or by separating the values within the print() function with commas. String interpolation uses a special sequence of characters, \( ), to include the value of variables and/or constants in the string. The following code shows how to do this:

var name = "Jon" 
var language = "Swift" 
 
var message1 = " Welcome to the wonderful world of " 
var message2 = "\(name), Welcome to the wonderful world of \(language)!" 
 
print(message2) 
print(name, message1, language, "!") 

We can also define two parameters in the print function that change how the message is displayed in the console. These parameters are the separator and terminator parameters. The separator parameter defines a string that is used to separate the values of the variables/constants in the print() function. By default, the print() function separates each variable/constant with a space. The terminator parameter defines what character is put at the end of the line. By default, the newline character is added at the end of the line.

The following code shows how we would create a comma-separated list that does not have a newline character at the end:

var name1 = "Jon"  
var name2 = "Kim"  
var name3 = "Kailey"  
var name4 = "Kara" 
 
print(name1, name2, name3, name4, separator:", ", terminator:"") 

There is one other parameter that we can add to our print() function: the to: parameter. This parameter will let us redirect the output of the print() function. In the following example, we redirect the output to a variable named line:

var name1 = "Jon" 
var name2 = "Kim" 
var name3 = "Kailey" 
var name4 = "Kara" 
 
var line = "" 
 
print(name1, name2, name3, name4, separator:", ", terminator:"", to:&line) 
print(line) 

Previously, the print() function was simply a useful tool for basic debugging, but now, with the new, enhanced print() function, we can use it for a lot more.

Summary

We began this chapter with a discussion on the Swift language and gave a brief history about it. We also mentioned some of the changes that will be present in Swift 5. We then showed you how to start and use playgrounds to experiment with Swift programming. We also covered the basic Swift language syntax and discussed proper language styles. This 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.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Fifth edition of this bestselling book, improved and updated to cover the latest version of the Swift 5 programming language
  • Get to grips with popular and modern design techniques to write easy-to-manage Swift code
  • Learn how to use core Swift features such as concurrency, generics, and copy-on-write in your code

Description

Over the years, the Mastering Swift book has established itself amongst developers as a popular choice as an in-depth and practical guide to the Swift programming language. The latest edition is fully updated and revised to cover the new version: Swift 5. Inside this book, you'll find the key features of Swift 5 easily explained with complete sets of examples. From the basics of the language to popular features such as concurrency, generics, and memory management, this definitive guide will help you develop your expertise and mastery of the Swift language. Mastering Swift 5, Fifth Edition will give you an in-depth knowledge of some of the most sophisticated elements in Swift development, including protocol extensions, error handling, and closures. It will guide you on how to use and apply them in your own projects. Later, you'll see how to leverage the power of protocol-oriented programming to write flexible and easier-to-manage code. You will also see how to add the copy-on-write feature to your custom value types and how to avoid memory management issues caused by strong reference cycles.

Who is this book for?

This book is for developers who want to delve into the newest version of Swift. If you are a developer and learn best by looking at and working with code, then this book is for you. A basic understanding of Apple's tools would be beneficial but not mandatory. All examples should work on the Linux platform as well.

What you will learn

  • Understand core Swift components, including operators, collections, control flows, and functions
  • Learn how and when to use classes, structures, and enumerations
  • Understand how to use protocol-oriented design with extensions to write easier-to-manage code
  • Use design patterns with Swift, to solve commonly occurring design problems
  • Implement copy-on-write for you custom value types to improve performance
  • Add concurrency to your applications using Grand Central Dispatch and Operation Queues
  • Implement generics to write flexible and reusable code
Estimated delivery fee Deliver to Thailand

Standard delivery 10 - 13 business days

$8.95

Premium delivery 5 - 8 business days

$45.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Apr 30, 2019
Length: 370 pages
Edition : 5th
Language : English
ISBN-13 : 9781789139860
Category :
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Thailand

Standard delivery 10 - 13 business days

$8.95

Premium delivery 5 - 8 business days

$45.95
(Includes tracking information)

Product Details

Publication date : Apr 30, 2019
Length: 370 pages
Edition : 5th
Language : English
ISBN-13 : 9781789139860
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 120.97
Hands-On Design Patterns with Swift
$48.99
Mastering Swift 5
$38.99
Swift Protocol-Oriented Programming
$32.99
Total $ 120.97 Stars icon
Banner background image

Table of Contents

19 Chapters
Taking the First Steps with Swift Chevron down icon Chevron up icon
Learning about Variables, Constants, Strings, and Operators Chevron down icon Chevron up icon
Optional Types Chevron down icon Chevron up icon
Using Swift Collections Chevron down icon Chevron up icon
Control Flow Chevron down icon Chevron up icon
Functions Chevron down icon Chevron up icon
Classes, Structures, and Protocols Chevron down icon Chevron up icon
Using Protocols and Protocol Extensions Chevron down icon Chevron up icon
Protocol Oriented Design Chevron down icon Chevron up icon
Generics Chevron down icon Chevron up icon
Availability and Error Handling Chevron down icon Chevron up icon
Custom Subscripting Chevron down icon Chevron up icon
Working with Closures Chevron down icon Chevron up icon
Concurrency and Parallelism in Swift Chevron down icon Chevron up icon
Custom Types Chevron down icon Chevron up icon
Memory Management Chevron down icon Chevron up icon
Swift Formatting and Style Guider Chevron down icon Chevron up icon
Adopting Design Patterns in Swift Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.8
(29 Ratings)
5 star 37.9%
4 star 27.6%
3 star 17.2%
2 star 13.8%
1 star 3.4%
Filter icon Filter
Top Reviews

Filter reviews by




Amazon Customer Dec 01, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I am new to Swift but have moderate experience in other languages, this book was very appropriate for my skill level. Hoffman uses meaningful examples that are succinct and effective.
Amazon Verified review Amazon
Agatha Yeung Nov 08, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is a good introduction for beginners. Also helpful if you know other languages (c#, java, python etc) and want to quickly learn Swift.
Amazon Verified review Amazon
Hobbes Doo Jun 16, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is a great reference to the Swift 5 language. It's great for beginners with some programming knowledge and experienced developers looking to learn Swift. My only complaint is that there are several errors throughout the book. If they were just typos I wouldn't mind, like "form" instead of "from", but they're code errors that would confuse a beginner and even hinder the understanding of the language. For example, in one chapter it shows a range type with a value 1..<20, meaning, the values go from 1 to 19, but the book says "0 to 19", and so on. Although annoying, this is not enough reason to not give this book and its author 5 stars. I'm really enjoying how well things are explained and with great examples, easy to follow.
Amazon Verified review Amazon
Daniel Kimball Jul 02, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Im new to swift and this is a great introduction.I’m learning a lot quickly so 5 stars. I wish the book had practice challenges and also there are errors here and there in chapter 7
Amazon Verified review Amazon
Jack N. Hatfield Feb 07, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Very complete coverage of Swift. Shows the strength and beauty of this new language. Easy to use, safe and new features that no doubt will be incorporated in other languages.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact [email protected] with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at [email protected] using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on [email protected] with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on [email protected] within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on [email protected] who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on [email protected] within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela