Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $11.99/month after trial. Cancel anytime.

Learning Swift - Second Edition
Learning Swift - Second Edition
Learning Swift - Second Edition
Ebook608 pages5 hours

Learning Swift - Second Edition

Rating: 0 out of 5 stars

()

Read preview

About this ebook

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

About This Book

- Write expressive, understandable, and maintainable Swift 2 code with this hands-on tutorial
- Unveil the complex underpinnings of Swift to turn your app ideas into reality
- This book is packed with real-life examples to help you implement concepts as you learn

Who This Book Is For

If you are looking to build iOS or OS X apps using the most modern technology, this book is ideal for you. You will find this book especially useful if you are new to programming or if you are yet to develop for iOS or OS X. No prior programming exposure is required.

What You Will Learn

- Form a solid understanding of the Swift 2 language
- Get to know the practical aspects of how a computer program actually works
- Understand the paradigms used by Apple’s frameworks so you are not intimidated by them
- Utilize the vast resources written in Objective-C to better inform your Swift programming
- Develop a basic portfolio of Swift code by learning the critical concepts
- Experience both object-oriented and functional programming
- Get to know the new coding techniques made available by Swift 2
- Discover resources to ensure you never stop becoming a better developer

In Detail

Swift is Apple’s new programming language and the future of iOS and OS X app development. It is a high-performance language that feels like a modern scripting language. On the surface, Swift is easy to jump into, but it has complex underpinnings that are critical to becoming proficient at turning an idea into reality.
This book is an approachable, 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.

Style and approach

This is an approachable, 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.
LanguageEnglish
Release dateMar 23, 2016
ISBN9781785883811
Learning Swift - Second Edition

Read more from Wagner Andrew J

Related to Learning Swift - Second Edition

Related ebooks

Internet & Web For You

View More

Related articles

Reviews for Learning Swift - Second Edition

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Learning Swift - Second Edition - Wagner Andrew J

    Table of Contents

    Learning Swift Second Edition

    Credits

    About the Author

    About the Reviewer

    www.PacktPub.com

    eBooks, discount offers, and more

    Why subscribe?

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

    Index

    Learning Swift Second Edition


    Learning Swift Second Edition

    Copyright © 2016 Packt Publishing

    All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

    Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

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

    First published: June 2015

    Second edition: March 2016

    Production reference: 1170316

    Published by Packt Publishing Ltd.

    Livery Place

    35 Livery Street

    Birmingham B3 2PB, UK.

    ISBN 978-1-78588-751-2

    www.packtpub.com

    Credits

    Author

    Andrew J Wagner

    Reviewer

    Guan Gui

    Commissioning Editor

    Kartikey Pandey

    Acquisition Editors

    Vivek Anantharaman

    Chaitanya Nair

    Content Development Editor

    Viranchi Shetty

    Technical Editor

    Saurabh Malhotra

    Copy Editors

    Kevin McGowan

    Sneha Singh

    Project Coordinator

    Izzat Contractor

    Proofreader

    Safis Editing

    Indexer

    Hemangini Bari

    Production Coordinator

    Shantanu N. Zagade

    Cover Work

    Shantanu N. Zagade

    About the Author

    Andrew J Wagner is a software developer who concentrates on iOS development and backend web services. He has a degree in computer engineering from Rensselaer Polytechnic Institute, New York. Currently, he works for a development shop named Chronos Interactive based in Denver, CO. He has experience of working with and for large-scale and small-scale companies, as well as running his own contracting and app companies. He is passionate about using computers as a creative outlet and writing software that is beautiful in implementation, functionality, and experience.

    When he isn't working or spending time with friends and family, he writes for his blog at http://drewag.me.

    I would like to thank my friends and family for being there for me as support for both my troubles and triumphs. Without their encouragement, I would not have finished this book or achieved any of the other things in my life that make me proud. An especially big thanks to my parents, Fern and Joe, for continually providing me with the tools I need to do the things I love.

    About the Reviewer

    Guan Gui graduated from the University of Melbourne. He implemented the first system of its kind for beekeepers using satellite sensory data to help them deploy their honeybees better. He is also a big fan of Apple. He started his own open source project—Uni Call (unicall.guiguan.net) for OS X. While his research focus is on machine learning, he enjoys the more practical side of CS: developing apps using Swift and JavaScript. Currently, he is trying to set his own start-up. Big ideas to change the world always spin in his head!

    www.PacktPub.com

    eBooks, discount offers, and more

    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 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://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

    Preface

    This book will help you to get started with Swift in no time. It helps you understand the nuances of iOS programming not only from a conceptual but also from an implementation perspective. This book is an invaluable resource if you are looking forward to exploring the world of iOS application programming.

    What this book covers

    Chapter 1, Introducing Swift, will take the reader through the process of installing Swift and running their first Swift program, in order to expose its power right away.

    Chapter 2, Building Blocks - Variables, Collections, and Flow Control, introduces you to the various built-in mechanisms Swift has for representing complex information in expressive and accessible ways, with the help of a real-world example.

    Chapter 3, One Piece at a Time - Types, Scopes, and Projects, introduces the tools necessary to closely model the real world with code. It will teach you how to define your own custom types using structures, classes, and enumerations. It also explores the concept of scope and access control.

    Chapter 4, To Be or Not To Be - Optionals, focuses on a special and critical type in Swift, called optionals. It includes a detailed explanation of how optionals work and how they can be used, which turns a seemingly complex topic into a very intuitive concept.

    Chapter 5, A Modern Paradigm - Closures and Functional Programming, introduces you to a new way of thinking about code called functional programming. We learn how Swift supports this technique and how we can apply it to our programs to make it even more understandable and expressive.

    Chapter 6, Make Swift Work For You - Protocols and Generics, describes what generics and protocols are and how they can provide power and safety at the same time.

    Chapter 7, Everything Is Connected - Memory Management, dives deeper into the inner-workings of Swift. We discuss how a computer stores information and how we can use that knowledge in combination with some new tools in Swift, to ensure that our code remains responsive and minimizes its effect on battery life.

    Chapter 8, Paths Less Traveled – Error Handling, goes into gracefully handling error situations in Swift with error throwing and catching.

    Chapter 9, Writing Code the Swift Way - Design Patterns and Techniques, introduces the reader to the art of programming by taking them through a number of specific design patterns that help reduce the complexity of code.

    Chapter 10, Harnessing the Past - Understanding and Translating Objective-C, develops a basic understanding of Objective-C with a focus on how it compares to Swift. This allows the reader to make use of the vast resources that exist in Objective-C to help with their Swift development.

    Chapter 11, A Whole New World - Developing an App, focuses on explaining the process of creating a real world iOS application, with the help of an example.

    Chapter 12, What's Next? - Resources, Advice, and the Next Steps, discusses how to move forward to become the best app developer you possibly can. It provides a list of resources and advice the reader can use to continue their Swift and app development learning process.

    What you need for this book

    To run the code in this book, you will need Xcode 7.2.

    Who this book is for

    If you want to build iOS or OS X apps using the most modern technology, this book is ideal for you. Learning Swift will place you into a small developer community that will explode in demand when all the development for Apple's platforms transitions to it. You will find this book especially useful if you are new to programming or if you have yet to develop for iOS or OS X.

    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.

    When mentioning pieces of code in text we will use the style as follows: You can see that Hello, playground" was indeed stored in the variable.

    If the code is longer it will presented as a block as follows:

    if invitees.count > 20 {

      println(Too many people invited)

    }

    else if invitees.count <= 3 {

        println(Not really a party)

    }

    else {

        println(Just right)

    }

    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: Now, click on Connect on the Remote Desktop Viewer. Keyboard shortcuts will be displayed using the key style.

    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 <feedback@packtpub.com>, 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 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.

    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

    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 http://www.packtpub.com/sites/default/files/downloads/LearningSwiftSecondEdition_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 <copyright@packtpub.com> 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 <questions@packtpub.com>, and we will do our best to address the problem.

    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 book

    Setting up the development environment

    Running our first Swift code

    Understanding playgrounds

    Learning 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.

    Running our first swift code

    We will start by creating a new Swift playground. As the name suggests, a playground is a place where you can play around with code. With Xcode open, navigate to File | New | Playground… from the menu bar, as shown in the following screenshot:

    Name it MyFirstPlayground, leave the platform as iOS, and save it wherever you wish.

    Once created, a playground window will appear with some code already populated inside it for you:

    You have already run your first Swift code. A playground in Xcode runs your code every time you make a change and shows you the code results in the sidebar, on the right-hand side of the screen.

    Let's break down what this code is doing. The first line is a comment that is ignored while being run. It can be really useful in adding extra information about your code inline with it. In Swift, there are two types of comments: single-line and multi-line. Single-line comments, such as the preceding one, always start with a //. You can also write comments that span multiple lines by surrounding them with /* and */. For example:

    /*

      This is a multi-line comment

      that takes up more than one line

      of code

    */

    As you can see in the preceding screenshot, the second line, import UIKit, imports a framework called UIKit. UIKit is the name of Apple's framework for iOS development. For this example, we are not actually making use of the UIKit framework so it is safe to completely remove that line of code.

    Finally, on the last line, the code defines a variable called str that is being assigned to the text Hello, playground. In the results sidebar, next to that line, you can see that Hello, playground was indeed stored in the variable. As your code becomes more complex, this will become incredibly useful to help you track and watch the state of your code, as it is run. Every time you make a change to the code, the results will update, showing you the consequences of the change.

    If you are familiar with other programming languages, many of them require some sort of line terminator. In Swift, you do not need anything like that.

    The other great thing about Xcode playgrounds is that they will show you errors as you type them in. Let's add a third line to the playground:

      var str = Something Else

    On its own, this is completely valid Swift code. It stores the text Something Else into a new variable called str. However, when we add this to the playground, we are shown an error in the form of a red exclamation mark next to the line number. If you click on the exclamation mark, you will be shown the full error:

    This line is highlighted in red and we are shown the Invalid redeclaration of 'str' error. This is because you cannot declare two different variables with the exact same name. Also, notice that the results along the right turned gray instead of black. This indicates that the result being shown is not from the latest code, but the last successful run of the code. The code cannot be successfully run to create a new result because of the error. If we change the second variable to strTwo, the error goes away:

    Tip

    Downloading the example code

    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.

    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

    Enjoying the preview?
    Page 1 of 1