41,99 €
Over 50 recipes to help you quickly and efficiently build applications with Swift 4 and Xcode 9
If you are looking for a book to help you learn about the diverse features offered by Swift 4 along with tips and tricks to efficiently code and build applications, then this book is for you. Basic knowledge of Swift or general programming concepts will be beneficial.
Swift 4 is an exciting, multi-platform, general-purpose programming language. Being open source, modern and easy to use has made Swift one of the fastest growing programming languages. If you interested in exploring it, then this book is what you need.
The book begins with an introduction to the basic building blocks of Swift 4, its syntax and the functionalities of Swift constructs. Then, introduces you to Apple's Xcode 9 IDE and Swift Playgrounds, which provide an ideal platform to write, execute, and debug the codes thus initiating your development process. Next, you'll learn to bundle variables into tuples, set order to your data with an array, store key-value pairs with dictionaries and you'll learn how to use the property observers. Later, explore the decision-making and control structures in Swift and learn how to handle errors in Swift 4.
Then you'll, examine the advanced features of Swift, generics and operators, and then explore the functionalities outside of the standard library, provided by frameworks such as Foundation and UIKit. Also, you'll explore advanced features of Swift Playgrounds. At the end of the book, you'll learn server-side programming aspect of Swift 4 and see how to run Swift on Linux and then investigate Vapor, one of the most popular server-side frameworks for Swift.
Each recipe addresses a specific problem, with a detailed discussion that explains the solution and offers insight into how it works.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 394
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: September 2017
Production reference: 1260917
ISBN 978-1-78646-089-9
www.packtpub.com
Author
Keith Moon
Copy Editor
Shaila Kusanale
Reviewer
Giordano Scalzo
Project Coordinator
Ulhas Kambali
Commissioning Editor
Ashwin Nair
Proofreader
Safis Editing
Acquisition Editor
Larissa Pinto
Indexer
Mariammal Chettiyar
ContentDevelopmentEditor
Onkar Wani
Graphics
Abhinash Sahu
Technical Editor
Akhil Nair
Production Coordinator
Shraddha Falebhai
Keith Moon is an award-winning iOS developer, author, and speaker based in London. He has worked with some of the biggest companies in the world to create engaging and personal mobile experiences. Keith has been developing in Swift since its release, working on projects both fully Swift, and mixed Swift and Objective-C. Keith has been invited to speak about Swift development in conferences from Moscow to Minsk and London.
Giordano Scalzo is a developer with 20 years of programming experience, since the days of the ZXSpectrum.
He has worked in C++, Java, .NET, Ruby, Python, and in a ton of other languages that he has forgotten the names of.
After years of backend development, over the past five years, Giordano has developed extensively for iOS, releasing more than 20 apps--apps that he wrote for clients, enterprise applications, or on his own.
Currently he is a contractor in London, where through his company Effective Code Ltd, http://effectivecode.co.uk, he delivers code for iOS aiming at quality and reliability.
In his spare time, when he is not crafting retro game clones for iOS, he writes his thoughts on http://giordanoscalzo.com.
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 e-mail 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
Sections
Getting ready
How to do it…
How it works…
There's more…
See also
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
Swift Building Blocks
Introduction
Your first Swift program
Getting ready
Downloading Xcode
How to do it...
There's more...
See also
Strings, Ints, Floats, and Bools
Getting ready
How to do it...
How it works...
There's more...
See also
Optionals, unwrap, and force unwrap
Getting started
How to do it...
How it works...
There's more...
See also
Functions
How to do it...
How it works...
There's more...
Default parameter values
Parameter overloading
See also
Object classes
Getting ready
How to do it...
How it works...
There's more...
See also
Structs
Getting ready
How to do it...
How it works...
There's more...
See also
Enumerations
Getting ready
How to do it...
How it works...
There's more...
Methods and computed variables
Associated values
See also
Closures
Getting ready
How to do it...
How it works...
There's more...
See also
Protocols
Getting ready
How to do it...
How it works...
There's more...
See also
Building on the Building Blocks
Introduction
Bundling variables into tuples
Getting ready
How to do it...
How it works...
There's more...
See also
Ordering your data with arrays
How to do it...
How it works...
There's more...
See also
Containing your data with sets
How to do it...
How it works...
Union
Intersection
Symmetric difference
Subtracting
There's more...
See also
Storing key-value pairs with Dictionaries
Getting ready
How to do it...
How it works...
There's more...
See also
Subscripts for custom types
Getting ready
How to do it...
How it works...
There's more...
See also
Changing your name with typealias
How to do it...
There's more...
See also
Getting property changing notifications using property observers
Getting ready
How to do it...
How it works...
There's more...
See also
Controlling access with access control
Getting ready
How to do it...
How it works...
There's more...
See also
Extending functionality with extensions
Getting ready
How to do it...
How it works...
There's more...
See also
Data Wrangling with Swift Control Flow
Introduction
Making decisions with if/else
Getting ready
How to do it...
How it works...
There's more...
Conditional unwrap
Chain unwrapping Optionals
Enum with associated values
See also
Switch it up
Getting ready
How to do it...
How it works...
See also
For the love of loops
How to do it...
How it works...
See also
While loops
Getting ready
How to do it...
How it works...
There's more...
See also
Try, throw, do and, catch - Swift error handling
How to do it...
How it works...
There's more...
See also
Checking up front with guard
How to do it...
How it works...
See also
Doing it later with defer
Getting ready
How to do it...
How it works...
There's more...
See also
Bailing out with fatalError and precondition
Getting ready
How to do it...
How it works...
See also
Generics, Operators, and Nested Types
Introduction
Using generics with types
How to do it...
How it works...
There's more...
See also
Using generics with functions
How to do it...
How it works...
There's more...
See also
Using generics with protocols
Getting ready
How to do it...
There's more...
See also
Advanced operators
Getting ready
How to do it...
See also
Option set
How to do it...
How it works...
See also
Create custom operators
Getting ready
How to do it...
How it works...
There's more...
See also
Nested types
Getting ready
How to do it...
How it works...
There's more...
See also
Beyond the Standard Library
Introduction
Foundation
Getting ready
How to do it...
How it works...
See also
Networking
How to do it...
How it works...
See also
JSON
Getting ready
How to do it...
There's more...
See also
XML
Getting ready
How to do it...
How it works...
There's more...
See also
Cocoa Touch
Getting ready
How to do it...
There's more...
See also
Swift Playgrounds
Introduction
Using Swift Playgrounds for UI
Getting ready
How to do it...
How it works...
There's more...
See also
Import Resources into Playgrounds
Getting ready
How to do it...
How it works...
See also
Import Code into Playgrounds
Getting ready
How to do it...
How it works...
See also
Multi-Page Playgrounds
Getting ready
How to do it...
How it works...
There's more...
See also
Server-Side Swift
Introduction
Swift on Ubuntu
Getting started
How to do it...
There's more...
Building a REST API using Vapor
Getting started
How to do it...
How it works...
There's more...
See also
Persistence with Vapor using Postgres
Getting started
How to do it...
There's more...
See also
Hosting your Vapor app on Heroku
Getting started
How to do it...
See also
Performance and Responsiveness in Swift
Introduction
Value and reference semantics
Getting ready
How to do it...
How it works...
See also
Dispatch Queues
Getting ready
How to do it...
How it works...
See also
Concurrent queues and dispatch groups
Getting ready
How to do it...
How it works...
See also
Operations
Getting ready
How to do it...
How it works...
There's more...
See also
Since Apple announced the Swift programming language at WWDC 2014, it has gone on to become one of the fastest growing programming languages. Swift is modern, open source, and easy to use, and therefore Swift's usefulness can extend beyond Apple's ecosystem, giving it the potential to be used across all platforms and for any scenario.
Swift 4 represents the latest version of this exciting new programming language, giving you the tools to build performant and responsive apps, with safe and clean code.
This book will guide you through Swift's features, building up your knowledge and toolset layer by layer, so you can use Swift to build the next great app or service.
You will be given useful, easy-to-follow recipes for using Swift to accomplish real-world tasks. Each recipe only uses concepts previously covered in the book, so you will never feel lost.
Learn what makes Swift one of the fastest growing and most exciting programming languages available today.
Chapter 1,Swift Building Blocks, introduces you to the basic building blocks of Swift 4, its syntax, and the functionalities of basic Swift constructs. Also, this chapter will introduce you to Apple’s Xcode 9 IDE and Swift Playgrounds, which provide an ideal way to create, execute, debug, and understand the recipes contained in this book, thus setting you up to initiate the development process. In this chapter, learn to write your first Swift program and understand the various basic elements of the Swift language.
Chapter 2,Building on the Building Blocks, teaches the reader to create more complex structures on the basis of the building blocks that you studied in the first chapter and the functionalities provided by the Swift standard library. You will get an understanding of how to bundle the variables into tuples, order the data with the help of an array, and store key-value pairs with Dictionaries. Also, you can learn to use the property observers and control the access to and visibility of your code. Then, you will also learn to extend the functionalities of your codes using the extensions.
Chapter 3, Data Wrangling with Swift Control Flow, says that programming is all about making decisions; therefore, this chapter explores how to make a decision on the basis of information gained and how to alter the control flow of the code. You can learn how to conditionally execute code with if/else statements, control the flow of execution of your code with switch statements, and then loop the code by understanding how to use thefor and while loops. Then, you will understand how to handle Swift errors with the try, throw, do, and catch statements, and also how a defer statement can be useful to change state once a function's execution is complete or to clean up values that are no longer needed.
Chapter 4, Generics, Operators, and Nested Types, provides you with an understanding of two of the advanced features of Swift, which are generics and operators. Using these features, you can learn to build functionalities that are flexible and well defined, and also understand how nested types allow logical grouping, access, and namespacing for your constructs.
Chapter 5, Beyond the Standard Library, takes you on a journey to explore the functionalities beyond the standard library, provided by frameworks such as Foundation and UIKit. Learning to use these functionalities will help you make full use of the Swift language.
Chapter 6, Swift Playgrounds, gives a total understanding of using Swift Playgrounds and explores advanced features, apart from those explored in the initial chapters, to create fully interactive experiences.
Chapter 7,Server-Side Swift, covers a totally different aspect of Swift programming, server-side programming with Swift. Also, you can gain an understanding of how to run Swift on Linux by installing the Swift toolchain, learn to use a web server framework to build a REST API, and host your API via a hosting service. Also, you can learn to accomplish your tasks easily by understanding how to use Vapor, one of the most popular frameworks in Swift 4.
Chapter 8, Performance and Responsiveness in Swift, concludes the book by exploring the more advanced concepts of Swift programming to gain an understanding of how certain Swift types are implemented and their performance characteristics. Also, it explains how to perform asynchronous tasks using Grand Central Dispatch. Then, it explores the multithreaded environment available on all Apple platforms and how to enhance the performance profile of your Swift constructs to build a fast and responsive app.
To follow along with the examples in this book, you will need a computer running macOS 10.12.6 or greater. You also need an Apple ID to download and install Xcode 9 from the Mac App Store. The chapter on server-side Swift also requires Ubuntu 16.04 LTS.
If you are looking for a book to help you learn about the diverse features offered by Swift 4, along with tips and tricks to efficiently code and build applications, then this book is for you. Basic knowledge of Swift or general programming concepts will be beneficial.
In this book, you will find several headings that appear frequently (Getting ready, How to do it…, How it works…, There's more…, and See also). To give clear instructions on how to complete a recipe, we use these sections as follows:
This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.
This section contains the steps required to follow the recipe.
This section usually consists of a detailed explanation of what happened in the previous section.
This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.
This section provides helpful links to other useful information for the recipe.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning. Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows:
"Next, we'll create the method that will take anIntand returnPoolBallType".
A block of code is set as follows:
func poolBallType(forNumber number: Int) -> PoolBallType { if number < 8 { return .solid } else if number > 8 { return .stripe } else { return .black } }
Any command-line input or output is written as follows:
brew install postgres
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "The repository landing page provides the structure and location of JSON configuration file underConfigure PostgreSQL".
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 e-mail [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 e-mailed directly to you. You can download the code files by following these steps:
Log in or register to our website using your e-mail 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
.
You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account. 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 for the book is also hosted on GitHub at https://github.com/PacktPublishing/Swift-4-Programming-Cookbook. 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 https://www.packtpub.com/sites/default/files/downloads/Swift4ProgrammingCookbook_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.
In this chapter, we will cover the following recipes:
Your first Swift program
Strings, Ints, Floats, and Bools
Optionals, unwrap, and force unwrap
Functions
Object classes
Structs
Enumerations
Closures
Protocols
Since Apple announced the Swift programming language at WWDC 2014, it has gone on to become one of the fastest growing programming language. TIOBE is a company that measures software quality and publishes a ranking index of programming language usage. At the time of writing, Swift ranks the 12th most popular language on this index and has overtaken Objective-C (visit http://www.tiobe.com/tiobe_index).
Swift is a modern, general purpose programming language that focuses on type safety, and an expressive and concise syntax. Seen as a replacement for the aging Objective-C, its use among Mac and iOS developers has skyrocketed, ensuring its place as the future of development on Apple's platforms.
While occupying this niche would alone ensure Swift's place as a useful and important programming language. Apple's decision to open source Swift's runtime and compiler have allowed Swift's influence to extend beyond Apple's ecosystem, giving it the potential to be used across all platforms and for any scenario.
Since open sourcing the Swift toolchain, Apple has provided support for running your Swift code on Linux. In the later chapters, we will investigate using a Swift server to execute your code. In addition, the release of the Swift Playgrounds iPad app, which happened alongside iOS 10, turns your tablet into a lightweight Integrated Development Environment (IDE). However, the simplest way to get up and running with Swift is still on Mac and with Apple's Xcode IDE. Therefore, this book will assume that this is also the development environment of the reader. Xcode also provides a perfect way to explore the structure and syntax of the Swift standard library, foundation, and any other framework available for iOS or Mac development in the form of its Playgrounds feature.
An Swift Playgrounds is a simplified environment for executing Swift code. For our purposes, Playgrounds provide an ideal way to create, execute, debug, and understand the recipes contained in this book. As such, it will also be assumed that the reader is using an Xcode Playground to implement the recipes contained in this book, unless otherwise stated.
Swift 3, released in 2016, presented a major step forward in standardizing the language syntax and, as a result, migrating code written in Swift 2 to Swift 3 was not always an easy task. Swift 4, by contrast, has been designed to be source compatible with Swift 3; therefore, the task of migrating between Swift 3 and Swift 4 should be minimal. Swift 4 has been available in a prerelease form since the beta release of Xcode 9, and will be finalized with the release of Xcode 9 and iOS 11. This book will use Swift 4 throughout, and differences from Swift 3 will be highlighted.
In this chapter, we will look at the building blocks of the Swift language, examining the syntax and functionality of the basic Swift constructs that everything else is based on.
All the code for this chapter can be found in GitHub repository at https://github.com/SwiftProgrammingCookbook/SwiftBuildingBlocks.
In the first recipe, we will get up and running with Swift using a Swift Playground, and we will run our first piece of Swift code.
To run our first Swift program, we need to download and install our IDE. During the beta of Apple's Xcode 9, it is available as a direct download from Apple's developer website at http://developer.apple.com/download, access to this beta will require a free Apple developer account. Once the beta has ended and Xcode 9 is publicly available, it will also be available from the Mac App Store. By obtaining it from the Mac App Store, you will be informed of updates automatically, so this is the preferred route once Xcode 9 is out of beta.
Follow these steps to download Xcode from the Mac App Store:
Open up the Mac App Store, either from the dock or via Spotlight:
Search for
xcode
:
Click on
Install
:
The progress can be monitored from Launchpad:
Follow these steps to get Xcode as a direct download:
Go to the Apple Developer download page at
http://developer.apple.com/download
:
Click on the
Download
button to download Xcode within a
.xip
file:
Double-click on the downloaded file to unpack the Xcode application.
Drag the Xcode application into your
Applications
folder:
With Xcode downloaded, let's create our first Swift playground:
Launch Xcode from the icon in your dock.
From the welcome screen, choose
Get started with a playground
:
From the template chooser, select the
blank
template from the
iOS
tab:
Choose a name for your playground and a location to save it:
You are now presented with a view that looks like this:
Let's replace the word
playground
with
Swift!
.
Click on the blue play icon in the bottom left-hand corner of the window to execute the code in the playground:
Congratulations! You have just run some Swift code.
On the right-hand side of the window, you will see the output of each line of code in the playground. We can see that our line of code has output
"Hello, Swift!"
:
If you put your cursor over the output on the right-hand side, you will see two buttons: one that looks like an eye and another that is a rounded square:
Click on the eye button to get a Quick Look box of the output. This isn't that useful for just a string, but can be useful for more visual output, such as colors and views:
Click on the square button, and a box will be added in-line, under your code, showing the output of the code. This can be really useful if you want to see how the output changes as you change the code:
We will learn more about playgrounds and how we can take them further in Chapter 6, Swift Playgrounds.
Some of the most basic operations in Swift, and any programming language, involve manipulating text and numbers, and determining true/false answers.
Let's take a look at the basic types in Swift that enable us to perform these operations. As we do that, we will learn how to assign constants and variables, and touch on Swift's static typing and mutability system.
Further information about these base types in Swift can be found in Apple's documentation of the Swift language:
Ints, Floats, and Bools
:
http://swiftbook.link/docs/the-basics
Strings and characters
:
http://swiftbook.link/docs/strings
In the real world, we don't always know the answer to a problem, and problems can occur if we blindly assume that someone does. The same is true in programming languages, especially when dealing with external systems that we may not control. In many languages, including Objective-C (until recently), there was no way to indicate that something being declared may not exist at the time you attempt to access it. This would lead to either fragile code that could have broken if a nil unexpectedly found its way in or tests being run all over the code to ensure that a value did exist where it was needed, which added complexity and increased the boilerplate code that had to be written.
With a focus on Swift being type-safe and making it easier to write safe code, this ambiguity had to be addressed, and the Swift language does this with the use of optionals.
