Mastering Swift
By Jon Hoffman
()
About this ebook
- Start with basic language features and progressively move to more advanced features
- Learn to use Xcode’s new Playground feature as you work through the immense number of examples in the book
- Learn what makes development with Swift so exiting and also get pointers on pitfalls to avoid
If you are a developer that 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.
Read more from Jon Hoffman
iOS and OS X Network Programming Cookbook Rating: 0 out of 5 stars0 ratingsMastering Swift 5: Deep dive into the latest edition of the Swift programming language, 5th Edition Rating: 0 out of 5 stars0 ratingsProtocol-Oriented Programming with Swift Rating: 0 out of 5 stars0 ratingsMastering Swift 3 Rating: 0 out of 5 stars0 ratingsMastering Swift 3 - Linux Rating: 0 out of 5 stars0 ratingsMastering Swift 4 - Fourth Edition Rating: 0 out of 5 stars0 ratingsSwift 3 Protocol-Oriented Programming - Second Edition Rating: 0 out of 5 stars0 ratingsSwift Protocol-Oriented Programming: Increase productivity and build faster applications with Swift 5, 4th Edition Rating: 0 out of 5 stars0 ratingsSwift: Developing iOS Applications Rating: 0 out of 5 stars0 ratingsMastering Arduino: A project-based approach to electronics, circuits, and programming Rating: 0 out of 5 stars0 ratings
Related to Mastering Swift
Related ebooks
Mastering Web Application Development with Express Rating: 0 out of 5 stars0 ratingsSwift Essentials - Second Edition Rating: 0 out of 5 stars0 ratingsSwiftUI Essentials - iOS Edition: Learn to Develop iOS Apps Using SwiftUI, Swift 5 and Xcode 11 Rating: 0 out of 5 stars0 ratingsSwift 2 Design Patterns Rating: 0 out of 5 stars0 ratingsFull Stack iOS Development with Swift and Vapor: Full stack iOS development made easy (English Edition) Rating: 0 out of 5 stars0 ratingsSwift iOS Programming for Kids Rating: 0 out of 5 stars0 ratingsSwift by Example Rating: 1 out of 5 stars1/5iOS 13 Programming for Beginners - Fourth Edition: Get started with building iOS apps with Swift 5 and Xcode 11, 4th Edition Rating: 0 out of 5 stars0 ratingsjQuery in Action Rating: 0 out of 5 stars0 ratingsLearn iOS Application Development: Take Your Mobile App Development Skills to the Next Level with Swift and Xcode (English Edition) Rating: 0 out of 5 stars0 ratingsSwift Cookbook Rating: 5 out of 5 stars5/5Swift in 30 Days: Build iOS Apps by Learning Swift, Xcode, and SwiftUI in Just Four Weeks (English Edition) Rating: 0 out of 5 stars0 ratingsLearning Swift - Second Edition Rating: 0 out of 5 stars0 ratingsApplication Development with Swift Rating: 0 out of 5 stars0 ratingsiOS Game Programming Cookbook Rating: 0 out of 5 stars0 ratingsSwift Functional Programming - Second Edition Rating: 3 out of 5 stars3/5JavaScript: The New Toys Rating: 0 out of 5 stars0 ratingsNode Cookbook: Second Edition Rating: 3 out of 5 stars3/5Twilio Cookbook: Second Edition Rating: 0 out of 5 stars0 ratingsSwift in Depth Rating: 0 out of 5 stars0 ratingsUltimate SwiftUI Handbook for iOS Developers: A complete guide to native app development for iOS, macOS, watchOS, tvOS, and visionOS Rating: 0 out of 5 stars0 ratingsCross-Platform Desktop Applications: Using Node, Electron, and NW.js Rating: 0 out of 5 stars0 ratingsApache Maven Cookbook Rating: 0 out of 5 stars0 ratingsSwift 5 for Absolute Beginners: Learn to Develop Apps for iOS Rating: 0 out of 5 stars0 ratingsSwiftUI For Dummies Rating: 0 out of 5 stars0 ratingsEssential TypeScript 4: From Beginner to Pro Rating: 0 out of 5 stars0 ratingsBuilding React Apps with Server-Side Rendering: Use React, Redux, and Next to Build Full Server-Side Rendering Applications Rating: 0 out of 5 stars0 ratingsIsomorphic Web Applications: Universal Development with React Rating: 0 out of 5 stars0 ratingsScratch Cookbook Rating: 0 out of 5 stars0 ratingsMastering Swift 5 - Fifth Edition: Deep dive into the latest edition of the Swift programming language, 5th Edition Rating: 0 out of 5 stars0 ratings
Programming For You
Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsLearn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5C# Programming from Zero to Proficiency (Beginner): C# from Zero to Proficiency, #2 Rating: 0 out of 5 stars0 ratingsLearn PowerShell in a Month of Lunches, Fourth Edition: Covers Windows, Linux, and macOS Rating: 5 out of 5 stars5/5Python Data Structures and Algorithms Rating: 5 out of 5 stars5/5HTML in 30 Pages Rating: 5 out of 5 stars5/5PYTHON: Practical Python Programming For Beginners & Experts With Hands-on Project Rating: 5 out of 5 stars5/5SQL: For Beginners: Your Guide To Easily Learn SQL Programming in 7 Days Rating: 5 out of 5 stars5/5Python QuickStart Guide: The Simplified Beginner's Guide to Python Programming Using Hands-On Projects and Real-World Applications Rating: 0 out of 5 stars0 ratingsLearning JavaScript Data Structures and Algorithms Rating: 5 out of 5 stars5/5Python Games from Zero to Proficiency (Beginner): Python Games From Zero to Proficiency, #1 Rating: 0 out of 5 stars0 ratingsC Programming For Beginners: The Simple Guide to Learning C Programming Language Fast! Rating: 5 out of 5 stars5/5Coding All-in-One For Dummies Rating: 0 out of 5 stars0 ratingsHTML & CSS: Learn the Fundaments in 7 Days Rating: 4 out of 5 stars4/5
Reviews for Mastering Swift
0 ratings0 reviews
Book preview
Mastering Swift - Jon Hoffman
Table of Contents
Mastering Swift
Credits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
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
1. Taking the First Steps with Swift
What is Swift?
Swift features
Playgrounds
Getting started with Playgrounds
iOS and OS X Playgrounds
Showing images in a Playground
Displaying graphs in Playgrounds
What Playgrounds are not
Swift language syntax
Comments
Semicolons
Parentheses
Curly braces
Assignment operator (=) does not return a value
Spaces are optional in conditional and assignment statements
Hello world
Summary
2. Learning about Variables, Constants, Strings, and Operators
Constants and variables
Defining constants and variables
Type safety
Type inference
Explicit types
Numeric types
Integers
Floating-point
The Boolean type
The string type
Optional variables
Enumerations
Operators
The assignment operator
Comparison operators
Arithmetic operators
The remainder operator
Increment and decrement operators
Compound assignment operators
The ternary conditional operator
The logical NOT operator
The logical AND operator
The logical OR operator
Summary
3. Using Collections and Cocoa Data Types
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
Adding two arrays
Reversing an array
Retrieving a subarray from an array
Making bulk changes to an array
Algorithms for arrays
sort
sorted
filter
map
Iterating over an array
Dictionaries
Creating and initializing dictionaries
Accessing dictionary values
Counting key/values in a dictionary
Is the dictionary empty?
Updating the value of a key
Adding a key-value pair
Removing a key-value pair
Tuples
Using Cocoa data types
NSNumber
NSString data type
NSArray
NSDictionary
Foundation data types
Summary
4. Control Flow and Functions
What we have learned so far
Curly brackets
Parentheses
Control flow
Conditional statements
The if statement
Executing codes with the if-else statement
The for loops
Using the for loop variant
Using the for-in loop variant
The while loop
Using the while loop
Using the do-while loop
The switch statement
Control transfer statements
The continue statement
The break statement
The fallthrough statement
Functions
Using a single parameter function
Using a multiparameter function
Defining a parameter's default values
Returning multiple values from a function
Returning optional values
Adding external parameter names
Using shorthand for external parameter names
Using variadic parameters
Parameters as variables
Using inout parameters
Nesting functions
Summary
5. 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
Initializer
Internal and external parameter names
Failable initializers
Inheritance
Overriding methods and properties
Overriding methods
Overriding properties
Preventing overrides
Protocols
Protocol syntax
Property requirements
Method requirements
Optional requirements
Extensions
Memory management
Reference versus value types
The working of ARC
Strong reference cycles
Summary
6. Working with XML and JSON Data
XML and JSON
Common files
XML and the NSXMLParser class
Using the NSXMLParserDelegate protocol
Parsing XML documents
XML and NSXMLDocument
XML and manually building XML documents
JSON and NSJSONSerialization
Parsing a JSON document
Creating a JSON document
Summary
7. Custom Subscripting
Introducing subscripts
Subscripts with Swift arrays
Read and write custom subscripts
Read only custom subscripts
Calculated subscripts
Subscript values
Subscripts with ranges
External names for subscripts
Multidimensional subscripts
When not to use a custom subscript
Summary
8. Using Optional Type and Optional Chaining
Introducing optionals
The need for optional types in Swift
Defining an optional
Using optionals
Unwrapping an optional
Optional binding
Returning optionals from functions, methods, and subscripts
Using optionals as a parameter in a function or method
Optional types with tuples
Optional chaining
The nil coalescing operator
Summary
9. Working with Generics
Introduction to generics
Generic functions
Generic types
Associated types
Summary
10. Working with Closures
Introducing closures
Simple closures
Shorthand syntax for closures
Using closures with Swift's array algorithms
Standalone closures and good style guidelines
Changing functionality
Select a closure based on results
Strong reference cycles with closures
Summary
11. Using Mix and Match
What is mix and match?
Using Swift and Objective-C together in the same project
Creating the project
Adding the Swift file 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
12. Concurrency and Parallelism in Swift
Concurrency and parallelism
Grand Central Dispatch
Creating and managing dispatch queues
Creating queues with the dispatch_queue_create() function
Creating concurrent dispatch queues with the dispatch_queue_create() function and using the dispatch_asynch() function
Creating a serial dispatch queue with the dispatch_queue_create() function and using the dispatch_sync() function
Requesting concurrent queues with the dispatch_get_global_queue() function
Requesting the main queue with the dispatch_get_main_queue() function
Using the dispatch_after() function
Using the dispatch_once() function
Using NSOperation and NSOperationQueue types
Using the NSBlockOperation implementation of NSOperation
Using the addOperationWithBlock() method of the operation queue
Subclassing the NSOperation class
Summary
13. 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
Classes
Functions and methods
Constants and variables
Indenting
Comments
Using the self keyword
Types
Constants and variables
Optional types
Use optional binding
Use optional chaining over optional binding for multiple unwrapping
Use type inference
Use shorthand declaration for collections
Use for-in loops over for loops
Use switch rather than multiple if statements
Don't leave commented out code in your application
Grand central dispatch
Set the attribute in the dispatch_queue_create() function
Use reverse DNS name for the tag parameter of the dispatch_queue_create() function
Use dispatch_get_global_queue() over dispatch_queue_create()
Summary
14. Network Development with Swift
What is network development?
An overview of the URL session classes
NSURLSession
NSURLSessionConfiguration
NSURLSessionTask
Using the NSURL class
NSMutableURLRequest
NSURLHTTPResponse
REST web services
Making an HTTP GET request
Making an HTTP POST request
Encoding a URL
Checking network connection
RSNetworking
RSURLRequest
RSTransaction and RSTransactionRequest
RSTransaction
RSTransactionRequest
Extensions
Summary
15. Adopting Design Patterns in Swift
What are design patterns?
Creational patterns
The singleton design pattern
The builder design pattern
The factory method pattern
Structural design patterns
The bridge pattern
The facade pattern
The proxy design pattern
Behavioral design patterns
The command design pattern
The strategy pattern
Summary
Index
Mastering Swift
Mastering Swift
Copyright © 2015 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
Production reference: 1230615
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78439-215-4
www.packtpub.com
Credits
Author
Jon Hoffman
Reviewers
Yasuhiro Inami
David McGraw
Ravi Shankar
Tatsuya Tobioka
Ye Xiaodong
Commissioning Editor
Sarah Crofton
Acquisition Editor
Usha Iyer
Content Development Editor
Anish Sukumaran
Technical Editor
Bharat Patil
Copy Editors
Merilyn Pereira
Laxmi Subramanian
Project Coordinator
Izzat Contractor
Proofreader
Safis Editing
Indexer
Tejal Soni
Production Coordinator
Melwyn D'sa
Cover Work
Melwyn D'sa
About the Author
Jon Hoffman has over 20 years of experience in the information technology field. Over those 20 plus years, Jon has worked in the areas of system administration, network administration, network security, development, and architecture. Currently, he works as a software engineer for Syntech Systems.
Over the past 7 years, Jon has developed extensively for the iOS platform. This includes several apps that he has published on the App Store, apps that he has written for third parties, and numerous enterprise applications. Packt Publishing also published Jon's first book, iOS and OS X Network Programming Cookbook.
What really drives Jon are the challenges in the information technology field, and there is nothing more exhilarating for him than overcoming a challenge. Some of Jon's other interests are watching baseball (go Sox!) and basketball (go Celtics!). Jon also really enjoys fishing, kayaking, and just being out on the lake with his family.
I would like to thank my wonderful wife, Kim; without her support, encouragement, patience, and understanding, this book could have never been written. I would also like to thank my two wonderful daughters, Kailey and Kara, who have both been my inspiration and driving force since the day they were born and to my dog, Buddy; maybe, one day I will be the person he thinks I am.
About the Reviewers
Yasuhiro Inami has been dedicated to software development for 6 years, which includes iOS apps with Objective-C. He creates messenger, camera, and news apps for work, and he also spends time on making open source projects, especially with the new and modern Swift language. You can find him at https://github.com/inamiy.
David McGraw is an entrepreneur and mobile consultant. He started building games for the iOS platform in 2008. He achieved success in 2011 after launching his third game, Colorflys. Colorflys spent most of 2011 being featured on iTunes, and reached the top 10 ranking on iPad.
In 2012, he formed Moonlit Solutions to help companies build successful mobile products. Since then, he has assisted established brands (Microsoft and AOL), small businesses, and several start-ups (Evomail and Tappy).
When Apple announced Swift in 2014, he was at WWDC and felt a surge of excitement. He has since built several projects using Swift and loves working with the language. He writes about Swift at http://www.xmcgraw.com and on Twitter at http://www.twitter.com/xmcgraw.
Ravi Shankar is a multiskilled software consultant with over 15 years of experience in the IT industry. He has a good, all-round ability to work on different technologies and extensive experience in product development, system maintenance, and support. He is a polyglot and a self-taught programmer with hands-on experience of Swift, Objective-C, and Java. He believes in gaining knowledge through sharing and helping others learn.
I would like to thank Izzat for patiently following up on reviewed content and Packt Publishing for giving me this opportunity.
Tatsuya Tobioka is a software engineer familiar with Ruby, JavaScript, Objective-C, and Swift. He lives happily with his beloved wife and children in Tokyo, Japan.
He started iOS development in 2010 and then released a number of apps for developers, such as JavaScript Anywhere, Edhita, and CoffeeScript At Once.
Currently, he spends much of his time learning React, Arduino, Go, and WatchKit.
You can check out his open source projects on GitHub at https://github.com/tnantoka and his tweets on Twitter. His Twitter handle is @tnantoka.
Ye Xiaodong is a full-stack software engineer and technical director of zai360.com, an O2O company that provides a recyclables collection service for Chinese family customers on a periodical basis. He has 7 years of application development experience working for startups and leading companies across the world on iOS, Android, Windows Phone, Symbian, and Meego. He has developed lots of iOS applications; designed, created, and maintained iOS libraries and Xcode plugins; and contributed to open source projects, as he is passionate about bringing the latest features to applications.
First and foremost, I would like to thank the coordinator of this project, Izzat Contractor, for her valuable guidance and advice, since this is my first time as a reviewer. Also, an honorable mention goes to my family, for their understanding and support while completing this project.
www.PacktPub.com
Support files, eBooks, discount offers, and more
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
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://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Free access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.
Preface
Swift is Apple's new programming language that was introduced at the WWDC (Worldwide Developers Conference) 2014, alongside the integrated development environment Xcode 6 and iOS 8. 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.
Swift can be thought of as Objective-C reimagined using modern concepts and safe programming patterns. In Apple's own words, Swift is like Objective-C without the C
. Chris Lattner, the creator of Swift, said Swift took language ideas from Objective-C, Rust, Haskell, Ruby, Python, C#, CLU, and far too many others to list.
In Apple's own words Swift is a successor to the C and Objective-C languages
; therefore, it is imperative for iOS and OS X developers who want to keep their skills up to date to not only learn but also master the Swift programming language.
The first five chapters of this book will introduce the reader to the Swift programming language. These chapters will give the reader a solid understanding of the Swift programming language. The remainder of the book will cover more advance topics such as concurrency, network development, and design patterns and will help the reader master the swift programming language.
This book is written in an example-based approach where each topic covered is backed by examples written to reinforce the topic and to show how to implement it within the reader's code.
Since Swift is constantly changing and evolving, the author has started a blog at http://masteringswift.blogspot.com to keep readers up to date with what is new in Swift. The blog will also be used to enhance and expand on the material in the book.
What this book covers
Chapter 1, Taking the First Steps with Swift, introduces the reader to the Swift programming language and discusses what inspired Apple to create Swift. We also go over the basic syntax of Swift and how to use Playgrounds to experiment and test Swift code.
Chapter 2, Learning about Variables, Constants, Strings, and Operators, explains to the reader about variables and constants in Swift and when to use them. There are brief overviews of the most common variable types, with examples of how to use them. We conclude this chapter by showing examples of how to use the most common operators in the Swift language.
Chapter 3, Using Collections and Cocoa Data Types, introduces Swift's Array and Dictionary collection types and shows examples of how to use them. We will also show how to use the Cocoa and Foundation data types with Swift.
Chapter 4, Control Flow and Functions, explains how to use Swift's control flow statements. These include looping, conditional, and control transfer statements. The second half of the chapter is all about functions and how to define and use them.
Chapter 5, Classes and Structures, explains Swift's classes and structures in detail. We will look at what makes them similar and what makes them different. We will also look at access controls and object-oriented design. We will close this chapter out by looking at memory management in Swift.
Chapter 6, Working with XML and JSON Data, starts off by discussing what XML and JSON data is and their uses. We then show several examples of how to parse and build XML and JSON data using Apple's frameworks.
Chapter 7, Custom Subscripting, examines how we can use custom subscripts in our classes, structures, and enumerations. Subscripts in Swift can be used to access elements in a collection. We can also define custom subscripts for our classes, structures, and enumerations.
Chapter 8, Using Optional Type and Optional Chaining, looks at what optional types really are, various ways to unwrap them, and optional chaining. For a developer just learning Swift, optional types can be one of the most confusing items to learn.
Chapter 9, Working with Generics, allows us to write very flexible and reusable code that avoids duplication. In this chapter, we will examine how Swift implements generics. We will also look at the proper ways to use generics in our code.
Chapter 10, Working with Closures, examines how to define and use closures in our code. We will conclude this chapter with a section on how to avoid strong reference cycles with closures. Closures in Swift are similar to blocks in Objective-C, except that they have a much cleaner and easier-to-use syntax.
Chapter 11, Using Mix and Match, examines mix and match and demonstrates how we can include Swift code in our Objective-C projects and Objective-C code in our Swift projects. With all of the apps and frameworks written in Objective-C, it was important to allow Swift and Objective-C code to work together.
Chapter 12, Concurrency and Parallelism in Swift, shows how to use both Grand Central Dispatch (GCD) and Operation Queues to add concurrency and parallelism to our applications. Understanding and knowing how to add concurrency and parallelism to our apps can significantly enhance the user experience.
Chapter 13, Swift Formatting and Style Guide, defines a style guide for the Swift language that can be a template for enterprise developers that need to create a style guide. Most enterprises have style guides for the various languages that they develop in.
Chapter 14, Network Development with Swift, looks at the Apple APIs to connect to remote severs and how to best use them. Network development can be both fun and challenging.
Chapter 15, Adopting Design Patterns in Swift, examines 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.
What you need for this book
To follow along with the examples in this book, the reader will need to have a Mac computer with OS X 10.10 or higher installed. They will also need to install Xcode version 6.3.1 or higher with Swift version 1.2 or higher.
Who this book is for
This book is intended for individuals looking for a book that not only gives them a solid introduction to the Swift programming language, but will also cover advanced topics such as ARC, Design Patterns, and Concurrency in depth. This book is written for the developer that learns best by looking at and working with code, because each concept covered in the book is backed by example code written to give the reader a good understanding of the current topic and to demonstrate how to properly implement it.
Conventions
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: To define a constant, you use the keyword let and to define a variable you use the keyword var.
A block of code is set as follows:
// Constants
let freezingTemperatureOfWaterCelsius = 0
let speedOfLightKmSec = 300000
// Variables
var currentTemperature = 22
var currentSpeed = 55
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: As we can see in the Timeline sidebar, our application will print the message Hello World! to the console.
Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Reader feedback
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.
Customer support
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.
Downloading the example code
You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. 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.
Downloading the color images of this book
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/2154OT_ColorImages.pdf.
Errata
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
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.
Questions
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.
Chapter 1. Taking the First Steps with Swift
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 programming became my career, it always remained more of a passion than a job, but over the past few years, that passion has 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 wonderful happened, Apple announced Swift. Swift is such an exciting and progressive language that it has brought a lot of that passion back and made programming fun for me again.
In this chapter, you will learn:
What is Swift?
What are some of the features of Swift?
What are Playgrounds?
How do you use Playgrounds?
What are the basic syntaxes of the Swift language?
What is Swift?
Swift is Apple's new programming language that was introduced at the Worldwide Developers Conference (WWDC) in 2014 alongside the integrated development environment Xcode 6 and iOS 8. 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 were able to keep Swift a secret for as long as they did and that no one suspected they were going to announce a new development language.
Swift can be thought of as Objective-C reimagined using modern concepts and safe programming patterns. In Apple's own words, Swift is like Objective-C without the C. Chris Lattner, the creator of Swift, said Swift took language ideas from Objective-C, Rust, Haskell, Ruby, Python, C#, CLU, and far too many others to list.
At WWDC 2014, Apple really stressed that Swift was Safe by Default. Swift is designed to eliminate many common programming errors, making applications more secure and less prone to bugs. As we look at Swift throughout this book, we will point out many ways in which Swift is safer than not only Objective-C, but also safer than most other modern languages.
The development of Swift 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 really contribute to Swift, and in July of 2013, it became a major focus of the Apple Developer Tools group.
Chris Lattner started at Apple in the summer of 2005. He has held several positions in the Developers Tools group and is currently the Director and Architect of that group. On his home page (http://www.nondot.org/sabre/), Chris notes that Xcode's Playground (more on Playgrounds a little later in this chapter) became a personal passion of his because it makes programming more interactive and approachable. We will be using Playgrounds a lot in the book as a test and experimentation platform.
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. Swift also provides seamless access to existing Cocoa frameworks. This gives Objective-C developers a certain amount of familiarity when they begin to learn Swift.
While there are a lot of similarities between Swift and Objective-C, there are also 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 alright 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, and eliminating bugs such as the Goto Fail bug in Apple's SSL library.
Mix and match allows us to create applications that contain both Objective-C and Swift files that can communicate with each other. This allows us to systematically update current Objective-C applications with Swift classes. It also allows us to use current Objective-C libraries/frameworks in our Swift applications.
Tip
Mix and match lets Objective-C and Swift files coexist in the same project. This allows us to begin using Swift without throwing away our existing Objective-C code base or projects.
Swift was also built to be fast. At WWDC 2014, Apple showed a number of benchmarks that showed Swift significantly outperformed Objective-C. Swift uses the LLVM compiler, which is included with Xcode 6 to transform the Swift code into highly optimized native code that is tuned to get the most out of Apple's modern hardware.
If you are an iOS or OS X developer and you are still not convinced that learning Swift is a good idea, then maybe this one paragraph from Apple's Swift page (https://developer.apple.com/swift/) will help convince you:
Swift is a successor to the C and Objective-C languages. It includes low-level primitives such as types, flow control, and operators. It also provides object-oriented features such as classes, protocols, and generics, giving Cocoa and Cocoa Touch developers the performance and power they demand.
The first line in that paragraph that says, Swift is a successor to the C and Objective-C languages
is the most important line. This line and other Apple documentation tells us that Apple sees the Swift language as its application and systems programming language of the future. While Objective-C is not going away anytime soon, it sounds like it will be taking a backseat to Swift in the very near future.
Swift features
When Apple said that Swift is Objective-C without the C, they are really only telling us half of the story. Objective-C is a superset of C and provides