Swift: Developing iOS Applications - Andrew J Wagner - E-Book

Swift: Developing iOS Applications E-Book

Andrew J Wagner

0,0
73,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Unleash the power of Swift and discover the skills required to build incredible robust iOS applications


About This BookWrite expressive, understandable, and maintainable Swift 2 code with this hands-on courseUnveil the complex underpinnings of Swift to turn your app ideas into realitySpecialize in developing real iOS apps, and 2D and 3D video games using Swift and CocoapodsDive deep into protocol extensions, learn new error handling model and use featured Swift design patterns to write more efficient codeWho This Book Is For


This course would be for app developers who are new to developing for iOS or OSX and are trying to get grips with Swift for the first time.


What You Will LearnFrom a solid understanding of the Swift 2 languageGet to know the practical aspects of how a computer program actually worksUnderstand the paradigms used by Apple's frameworks, so you are not intimidated by themCreate a server in Swift to deliver JSON data to an iOS appTake advantage of Cocoapods to use third-party librariesBuild games with SpriteKit and SceneKitDevelop an app running on the cloud to act as an API server for your client's appsDive into the core components of Swift 2 including operators, collections, control flow, and functionsCreate and use classes, structures, and enums including object-oriented topics such as inheritance, protocols, and extensionsDevelop a practical understanding of subscripts, optionals, and closuresMaster Objective-C interoperability with mix and matchAccess network resources using SwiftImplement various standard design patterns in the Swift languageIn Detail


The Swift––Developing iOS Applications course will take you on a journey to become an efficient iOS and OS X developer, with the latest trending topic in town. Right from the basics to the advanced level topics, this course would cover everything in detail. We'll embark our journey by dividing the learning path into four modules. Each of these modules are a mini course in their own right; and as you complete each one, you'll gain key skills and be ready for the material in the next module.


The first module is like a step-by-step guide to programming in Swift 2. Each topic is separated into compressible sections that are full of practical examples and easy-to-understand explanations. Each section builds on the previous topics, so you can develop a proficient and comprehensive understanding of app development in Swift 2. By the end of this module, you'll have a basic understanding of Swift 2 and its functionalities.


The second module will be the an easy-to-follow guide filled with tutorials to show you how to build real-world apps. The difficulty and complexity level increases chapter by chapter. Each chapter is dedicated to build a new app, beginning from a basic and unstyled app through to a full 3D game. The last two chapters show you how to build a complete client-server e-commerce app right from scratch. You'll be able to build well-designed apps, effectively use AutoLayout, develop videogames, and build server apps.


The third and the last module of our course will take an example-based approach where each concept covered is supported by example code to not only give you a good understanding of the concept, but also to demonstrate how to properly implement it.


Style and approach


This course includes all the resources that will help you jump into the app development .This course covers all the important aspects Swift application development and is divided into individual modules so that you develop your skill after the completion of a module and get ready for the next. Through this comprehensive course, you'll learn how to use Swift programming with hands-on examples from scratch to finish!

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 1203

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Swift: Developing iOS Applications
Swift: Developing iOS Applications
Credits
Preface
What this learning path covers
What you need for this learning path
Who this learning path is for
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Module 1
1. Introducing Swift
Defining our goals for this book
Setting up the development environment
Running our first swift code
Understanding playgrounds
Learning with this book
Summary
2. Building Blocks – Variables, Collections, and Flow Control
Core Swift types
Constants and variables
Containers
Tuples
Arrays
Dictionaries
Swift's type system
Printing to the console
Control flow
Conditionals
Switches
Loops
Functions
Basic functions
Parameterized functions
Functions that return values
Functions with default arguments
Guard statement
Bringing it all together
Summary
3. One Piece at a Time – Types, Scopes, and Projects
Structs
Types versus instances
Properties
Member and static methods
Computed properties
Reacting to property changes
Subscripts
Custom initialization
Classes
Inheriting from another class
Initialization
Overriding initializer
Required initializer
Designated and convenience initializers
Overriding methods and computed properties
Methods
Computed properties
Casting
Upcasting
Downcasting
Enumerations
Basic declaration
Testing enumeration values
Raw values
Associated values
Methods and properties
Projects
Setting up a command-line Xcode project
Creating and using an external file
Interfacing with code from other files
File organization and navigation
Extensions
Scope
How scope is defined
Nested types
Access control
Summary
4. To Be or Not To Be – Optionals
Defining an optional
Unwrapping an optional
Optional binding
Forced unwrapping
Nil coalescing
Optional chaining
Implicitly unwrapped optionals
Debugging optionals
The underlying implementation
Summary
5. A Modern Paradigm – Closures and Functional Programming
Functional programming philosophy
State and side effects
Declarative versus imperative code
Closures
Closures as variables
Closures as parameters
Syntactic sugar
Building blocks of functional programming in Swift
Filter
Reduce
Map
Sort
How these affect the state and nature of code
Lazy evaluation
Example
Summary
6. Make Swift Work For You – Protocols and Generics
Protocols
Defining a protocol
Implementing a protocol
Using type aliases
Generics
Generic function
Generic type
Type constraints
Protocol constraints
Where clauses for protocols
Where clauses for equality
Extending generics
Adding methods to all forms of a generic
Adding methods to only certain instances of a generic
Extending protocols
Putting protocols and generics to use
Generators
Sequences
Product of Fibonacci numbers under 50
Summary
7. Everything Is Connected – Memory Management
Computer data storage
File system
Memory
Value types versus reference types
Determining value type or reference type
Behavior on assignment
Behavior on input
Closure capture behavior
Automatic reference counting
Object relationships
Strong
Weak
Unowned
Strong reference cycles
Between objects
Spotting
Fixing
With closures
Spotting
Fixing
Lost objects
Between objects
With closures
Structures versus classes
Summary
8. Paths Less Traveled – Error Handling
Throwing errors
Defining an error type
Defining a function that throws an error
Implementing a function that throws an error
Handling errors
Forceful try
Optional try
Catching an error
Propagating errors
Cleaning up in error situations
Order of execution when errors occur
Deferring execution
Summary
9. Writing Code the Swift Way – Design Patterns and Techniques
What is a design pattern?
Behavioral patterns
Iterator
Observer
Callback
Notification center
Structural patterns
Composite
Hierarchies
Alternative to subclassing
Delegate
Model view controller
Creational patterns
Singleton/shared instance
Abstract factory
Using associated values effectively
Replacing class hierarchies
Concisely representing state
Extending system types to reduce code
Lazy properties
Avoiding unnecessary memory usage
Avoiding unnecessary processing
Localizing logic to the concerned property
Summary
10. Harnessing the Past – Understanding and Translating Objective-C
Swift's relationship to Objective-C
Background of Objective-C
Constants and variables
Value types
Reference types
Containers
Arrays
Dictionaries
Control flow
Conditionals
Switches
Loops
Functions
Types
Structures
Enumerations
Classes
Basic class
Initializers
Properties
Methods
Inheritance
Categories
Protocols
Blocks
Projects
Header files
Implementation files
Organization
Calling Objective-C code from Swift
Bridging header
Using functions
Using types
Containers
Annotations
Nullability
Container element types
Summary
11. A Whole New World – Developing an App
Conceptualizing the app
Features
Interface
Data
Setting up the app project
Configuring the user interface
Running the app
Allowing picture taking
Temporarily saving a photo
Populating our photo grid
Refactoring to respect model-view-controller
Permanently saving a photo
Summary
12. What's Next? – Resources, Advice, and the Next Steps
Apple's documentation
Forums and blogs
Blog posts
Forums
Prominent figures
Podcasts
Summary
2. Module 2
1. Welcome to the World of Swift
The first look at Swift
Let's go to the playground
The building blocks – variables and constants
Collecting variables in containers
Controlling the flow
Transforming the values using functions
Structs – custom compound types
Classes – common behavior objects
Loose coupling with protocols
Composing objects using protocol extensions
Checking the existence of an optional value
Enumerations on steroids
Extended pattern matching
Catching errors
Swift functional programming patterns
Summary
2. Building a Guess the Number App
The app is…
Building a skeleton app
Adding the graphics components
Connecting the dots
Adding the code
Summary
3. A Memory Game in Swift
The app is…
Building the skeleton of the app
The menu screen
Implementing the basic menu screen
Creating a nice menu screen
The game screen
The structure
Adding a collection view
Sizing the components
Connecting the dataSource and the delegate
Implementing a deck of cards
What we are expecting
The card entity
Crafting the deck
Shuffling the deck
Finishing the deck
Put the cards on the table
Adding the assets
The CardCell structure
Handling touches
Finishing the game
Implementing the game logic
We got a pair
We made the wrong move
Et voilà! The game is completed
Summary
4. A TodoList App in Swift
The app is…
Building a skeleton app
Implementing an empty app
Adding third-party libraries with CocoaPods
Implementing the Todos view controller
Building the Todos screen
Adding entities
Implementing datastore
Connecting datastore and View Controller
Configuring tableView
Finishing touches
Swipe that cell!
Adding a Todo task
The add a Todo view
The add a Todo View Controller
Finishing TodoDatastore
List View Controller
Where do we go from here?
Summary
5. A Pretty Weather App
The app is…
Building the skeleton
Creating the project
Adding assets
Implementing the UI
The UI in blocks
Completing the UI
Implementing CurrentWeatherView
Building WeatherHourlyForecastView
Seeing the next day's forecast in WeatherDaysForecastView
Blurring the background
Downloading the background image
Searching in Flickr
Geolocalising the app
Using Core Location
Retrieving the actual forecast
Getting the forecast from OpenWeatherMap
Rendering CurrentWeatherView
Rendering WeatherHourlyForecastView
Rendering WeatherDaysForecastView
Connecting to the server
Where do we go from here?
Summary
6. Flappy Swift
The app is…
Building the skeleton of the app
Creating the project
Implementing the menu
A stage for a bird
SpriteKit in a nutshell
Explaining the code
Simulating a three-dimensional world using parallax
How to implement scrolling
A flying bird
Adding the Bird node
Making the bird flap
Pipes!
Implementing the pipes node
Making the components interact
Setting up the collision-detection engine
Completing the game
Colliding with pipes
Adding the score
Adding a restart pop-up
Summary
7. Polishing Flappy Swift
Adding juiciness
Let there be sounds!
Playing the soundtrack
Shaking the screen!
Integrating with Game Center
What Game Center provides
Setting up Game Center
Creating an app record on iTunes Connect
Enabling Game Center
Creating fake user accounts to test Game Center
Authenticating a player
Summary
8. Cube Runner
The app is…
Introduction to SceneKit
What is SceneKit?
Building an empty scene
Adding a green torus
Let there be light!
Let's make it move!
Implementing Cube Runner
The game skeleton
Implementing the menu
Flying in a 3D world
Setting up a scene
Adding a fighter
Texturing the world
Make it move
Adding cubes
Adding more obstacles
Adding a few touches
The score
Let's add music
Summary
9. Completing Cube Runner
Creating a real game
Detecting collisions
Game over!
Adding the juice
Game Center
Summary
10. ASAP – an E-commerce App in Swift
The app is…
The first requirement: login and registration
The second requirement: the products grid
The third requirement: the open cart
The skeleton app and register screen
The skeleton app
The ASAP e-commerce store
The e-commerce product list
The product cell
Parsing and storing products
The ASAP cart
Adding a product to the cart
Removing items from cart and checkout
Summary
11. ASAPServer, a Server in Swift
The interface of the ASAP Server
One skeleton server for two OSes
An OS X skeleton server
Preparing the OS X environment
The HelloWorld skeleton server
Preparing the Linux environment
The ASAPServer
The Products
The cart
The order
Connecting the ASAP app
The products
The Cart
The order
Summary
3. Module 3
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
Creating and displaying graphs in Playgrounds
What Playgrounds are not
Swift language syntax
Comments
Semicolons
Parentheses
Curly braces
An 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
sortInPlace
sort
filter
map
forEach
Iterating over an array
Dictionaries
Creating and initializing dictionaries
Accessing dictionary values
Counting key or values in a dictionary
Is the dictionary empty?
Updating the value of a key
Adding a key-value pair
Removing a key-value pair
Set
Initializing a set
Inserting items into a set
The number of items in a set
Checking whether a set contains an item
Iterating over a set
Removing items in a set
Set operations
Tuples
Using Cocoa data types
NSNumber
NSString
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
Conditional code execution 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 repeat-while loop
The switch statement
Using case and where statements with conditional statements
Filtering with the where statement
Filtering with the for-case statement
Using the if-case statement
Control transfer statements
The continue statement
The break statement
The fallthrough statement
The guard 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 variadic parameters
Parameters as variables
Using inout parameters
Nesting functions
Putting it all together
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
Custom initializers
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. Using Protocols and Protocol Extensions
Protocols as types
Polymorphism with protocols
Type casting with protocols
Protocol extensions
Summary
7. Writing Safer Code with Availability and Error Handling
Error handling prior to Swift 2.0
Error handling in Swift 2
Representing errors
Throwing errors
Catching errors
The availability attribute
Summary
8. 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
9. 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
10. Using Optional Types
Introducing optionals
The need for optional types in Swift
Defining an optional
Using optionals
Forced 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
11. Working with Generics
An introduction to generics
Generic functions
Generic types
Associated types
Summary
12. Working with Closures
An introduction to closures
Simple closures
Shorthand syntax for closures
Using closures with Swift's array algorithms
Standalone closures and good style guidelines
Changing functionality
Selecting a closure based on results
Creating strong reference cycles with closures
Summary
13. Using Mix and Match
What is mix and match
Using Swift and Objective-C together in the same project
Creating the project
Adding 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
14. 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
Creating a serial dispatch queue with the dispatch_queue_create() 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
15. 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 a reverse DNS name for the tag parameter of the dispatch_queue_create() function
Use dispatch_get_global_queue() over dispatch_queue_create()
Summary
16. 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
Checking network connection
RSNetworking2 for Swift 2
RSURLRequest
RSTransaction and RSTransactionRequest
RSTransaction
RSTransactionRequest
Extensions
Summary
17. Adopting Design Patterns in Swift
Value versus reference types
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 façade pattern
The proxy design pattern
Behavioral design patterns
The command design pattern
The strategy pattern
Summary
A. Biblography
Index

Swift: Developing iOS Applications

Swift: Developing iOS Applications

Unleash the power of Swift and discover the skills required to build incredible robust iOS applications.

A course in three modules

BIRMINGHAM - MUMBAI

Swift: Developing iOS Applications

Copyright © 2016 Packt Publishing

All rights reserved. No part of this course 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 course to ensure the accuracy of the information presented. However, the information contained in this course is sold without warranty, either express or implied. Neither the authors, 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 course.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this course by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Published on: August 2016

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78712-024-2

www.packtpub.com

Credits

Authors

Andrew J Wagner

Giordano Scalzo

Jon Hoffman

Reviewers

Guan Gui

Hugo Solis

Jannis Muething

Content Development Editor

Sumeet Sawant

Production Coordinator

Arvind Kumar Gupta

Preface

At their Worldwide Developer's conference (WWDC) in 2015, Apple announced Swift 2, a major update to the innovative programming language they first unveiled to the world the year before. Swift 2 features exciting enhancements to the original iteration of Swift, acting, as Apple put it themselves as "a successor to the C and Objective-C languages." Swift is a user-friendly language with a smooth learning curve; it is safe, robust, and really flexible.

Swift 2 is more powerful than ever; it introduces new ways to solve old problems, more robust error handling, and a new programming paradigm that favours composition over inheritance.

What this learning path covers

Module 1, Learning Swift Second Edition, is a step-by-step introduction into programming with Swift for everyone. It begins by giving you an overview of the key features through practical examples and progresses to more advanced topics that help differentiate the proficient developers from the mediocre ones. It covers important concepts such as Variables, Optionals, Closures, Generics, and Memory Management. Mixed in with those concepts, it also helps you learn the art of programming such as maintainability, useful design patterns, and resources to further your knowledge. This all culminates in writing a basic iOS app that will get you well on your way to turning your own app ideas into reality.

Module 2, Swift 2 By Example, is a fast-paced, practical guide to help you learn how to develop iOS apps using Swift. Through the development of seven different iOS apps and one server app, you'll find out how to use either the right feature of the language or the right tool to solve a given problem.

We begin by introducing you to the latest features of Swift 2, further kick-starting your app development journey by building a guessing game app, followed by a memory game. It doesn't end there, with a few more apps in store for you: a to-do list, a beautiful weather app, two games: Flappy Swift and Cube Runner, and finally an ecommerce app to top everything off.

Module 3, Mastering Swift 2, will teach you how to harness the newest features of Swift 2 todevelop advanced applications on a wide range of platforms with this cutting-edge development guide. Exploring and demonstrating how to tackle advanced topics such as Objective-C interoperability, ARC, closures, and concurrency, you'll develop your Swift expertise and become even more fluent in this vital and innovative language. With examples that demonstrate how to put the concepts into practice, and design patterns and best practices, you'll be writing better iOS and OSX applications in with a new level of sophistication and control..

What you need for this learning path

You'll need the following software for the X code 7 and OS X 10.10.4 or later

Who this learning path is for

This course would be for app developers who are new to developing for iOS or OSX and are trying to get grips with Swift for the first time.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this course—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 course'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 course, 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 for this course from your account at http://www.packtpub.com. If you purchased this course 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 course in the Search box.Select the course for which you're looking to download the code files.Choose from the drop-down menu where you purchased this course from.Click on Code Download.

You can also download the code files by clicking on the Code Files button on the course's webpage at the Packt Publishing website. This page can be accessed by entering the course'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 WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

The code bundle for the course is also hosted on GitHub at https://github.com/PacktPublishing/Swift-Developing-iOS-Applications. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

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 courses—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 course. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your course, 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 course 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 course, you can contact us at <[email protected]>, and we will do our best to address the problem.

Part 1. Module 1

Learning Swift - Second Edition

Develop the skills required to create compelling, maintainable, and robust iOS and OS X apps with Swift

Chapter 1. Introducing Swift

What are you trying to achieve by reading this book? Learning Swift can be fun, but most of us are trying to achieve something bigger. There is something we want to create, a career we want to follow, or maybe something else entirely. Whatever that goal is, I encourage you to keep it in mind as you read this book. It will be much easier for you to learn, from this or any other resource, if you can always relate it to your goal.

With that in mind, before we dive into learning Swift, we have to understand what it really is and how it will help us in achieving our goals. We also need to move forward with an effective learning technique and get a taste of what is to come. To do all of that, we will cover the following topics in this chapter:

Defining our goals for this bookSetting up the development environmentRunning our first Swift codeUnderstanding playgroundsLearning with this book

Defining our goals for this book

Swift is a programming language developed by Apple primarily to allow developers to continue to push their platforms forward. It is their attempt to make iOS, OS X, watchOS, and tvOS app development more modern, safe, and powerful.

However, Apple has also released Swift as Open Source and begun an effort to add support for Linux with the intent to make Swift even better and a general purpose programming language available everywhere. Some developers have already begun using it to create command-line scripts as a replacement/supplement of the existing scripting languages, such as Python or Ruby and many can't wait to be able to share some of their app code with Web backend code. Apple's priority, at least for now, is to make it the best language possible, to facilitate app development. However, the most important thing to remember is that modern app development almost always requires pulling together multiple platforms into a single-user experience. If a language could bridge those gaps and stay enjoyable to write, safe, and performant, we would have a much easier time making amazing products. Swift is well on its way to reach that goal.

Now, it is important to note that learning Swift is only the first step towards developing. To develop for a device, you must learn the programming language and the frameworks the device maker provides. Being skilled with a programming language is the foundation of getting better at using frameworks and ultimately building apps.

Developing software is like building a table. You can learn the basics of woodworking and nail a few pieces of wood together to make a functional table, but you are very limited in what you can do because you lack advanced woodworking skills. If you want to make a truly great table, you need to step away from the table and focus first on developing your skill set. The better you are at using the tools, the greater the number of possibilities that open up to you to create a more advanced and higher quality piece of furniture. Similarly, with a very limited knowledge of Swift, you can start to piece together a functional app from the code you find online. However, to really make something great, you have to put the time and effort into refining your skill set with the language. Every language feature or technique that you learn opens up more possibilities for your app.

That being said, most developers are driven by a passion to create things and solve problems. We learn best when we can channel our passions into truly improving ourselves and the world around us. We don't want to get stuck learning the minutia of a language with no practical purpose.

The goal of this book is to develop your skills and confidence to dive passionately into creating compelling, maintainable, and elegant apps in Swift. To do that, we will introduce the syntax and features of Swift in a practical way. You will build a rich toolset, while seeing that toolset put to real world usage. So, without further ado, let's jump right into setting up our development environment.

Setting up the development environment

In order to use Swift, you will need to run OS X, the operating system that comes with all Macs. The only piece of software that you will need is called Xcode (version 7 and higher). This is the environment that Apple provides, which facilitates development for its platforms. You can download Xcode for free from the Mac App Store at www.appstore.com/mac/Xcode.

Once downloaded and installed, you can open the app and it will install the rest of Apple's developer tool components. It is as simple as that! We are now ready to run our first piece of Swift code.

Understanding playgrounds

A playground is not truly a program. While it does execute code like a program, it is not really useful outside of the development environment. Before we can understand what the playground is doing for us, we must first understand how Swift works.

Swift is a compiled language, which means that for Swift code to be run, it must first be converted into a form that the computer can actually execute. The tool that does this conversion is called a compiler. A compiler is actually a program and it is also a way to define a programming language.

The Swift compiler takes the Swift code as input and, if it can properly parse and understand the code, outputs machine code. Apple developed the Swift compiler to understand the code according to a series of rules. Those rules are what define the Swift programming language and those rules are what we are trying to learn, when we say we are learning Swift.

Once the machine code is generated, Xcode can wrap the machine code up inside an app that users can run. However, we are running Swift code inside our playground, so clearly building an app is not the only way to run code; something else is going on here.

Every time you make a change to a playground, it automatically tries to compile your code. If it is successful, instead of wrapping up the machine code in an app to be run later, it runs the code immediately and shows you the results. If you had to do this process yourself, you would first have to consciously make the decision to build the code into an app and then run it when you wanted to test something. This would be a huge waste of time; especially, if you write an error that you don't catch until the moment you decide to actually run it. The quicker you can see the result of a code change, the faster you will be at developing the code and the fewer mistakes you will make.

For now, we will be developing all of our code inside a playground because it is a fantastic learning environment. Playgrounds are even more powerful than what we have seen so far and we will see that as we explore deeper into the Swift language.

We are just about ready to get to the meat of learning Swift, but first let's take a moment to make sure that you can get the most out of this book.

Learning with this book

The learning process of this book follows very closely to the philosophy behind playgrounds. You will get the most out of this book if you play around with the code and ideas that we discuss. Instead of just passively reading through this, glancing at the code, put the code into a playground, and observe how it really works. Make changes to the code, try to break it, try to extend it, and you will learn far more. If you have a question, don't default to looking up the answer, try it out.

At its core, programming is a creative exercise. Yes, it requires the ability to think logically through a problem, but nine times out of ten there is no right way there is no correct answer. Technology is pushed by those of us who won't settle for the accepted solution, who aren't OK with following a fixed set of instructions, who want to push the boundaries. As we move forward in learning Swift, make this book and Swift work for you by not taking everything at face value.

Summary

We're off to a good start. We've gone over how Swift is a language designed primarily for app development, which often includes multiple different platforms. We already ran our first code and learned a little bit about how a computer runs it indirectly by first compiling it into a form it understands how to run. Most importantly, we've learned that you will learn best from this book by having a goal to work towards and by playing around with the concepts as you read along. So let's get started!

Next, we will start breaking down the basics of Swift and then put them together to make our first program.

Printing to the console

It is very useful to write output to a log so that you can trace the behavior of code. As a codebase grows in complexity, it gets hard to follow the order in which things happen and exactly what the data looks like as it flows through the code. Playgrounds help a lot with this but it is not always enough.

In Swift, this process is called printing to the console. To do this, you use something called print. It is used by writing print followed by text surrounded by parentheses. For example, to print Hello World! to the console, the code would look like this:

print("Hello World!")

If you put that code in a playground, you would see Hello World! written in the results pane. However, this is not truly the console. To view the console, you can go to View | Debug Area | Show Debug Area. A new view will appear at the bottom of the window and it will contain all text the code has printed to the console:

Not only can you print static text to the console, you can also print out any variable. For example, if you wanted to print out the name variable, you would write:

print(name)

You can even use a feature of Swift called string interpolation to insert variables into a string, like this:

print("Hello \(name)!")

At any point in a string literal, even when not printing, you can insert the results of the code by surrounding the code with \( and ). Normally this would be the name of a variable but it could be any code that returns a value.

Printing to the console is even more useful when we start using more complex code.