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

Only $11.99/month after trial. Cancel anytime.

Learning Swift
Learning Swift
Learning Swift
Ebook556 pages5 hours

Learning Swift

Rating: 5 out of 5 stars

5/5

()

Read preview

About this ebook

About This Book
  • Practically write expressive, understandable, and maintainable Swift code
  • Discover and optimize the features of Swift to write cleaner and better code
  • This is a step-by-step guide full of practical examples to create efficient IOS applications
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 have yet to develop for iOS or OS X.

LanguageEnglish
Release dateJun 30, 2015
ISBN9781784399627
Learning Swift

Read more from Wagner Andrew J

Related to Learning Swift

Related ebooks

Programming For You

View More

Related articles

Reviews for Learning Swift

Rating: 5 out of 5 stars
5/5

1 rating0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Learning Swift - Wagner Andrew J

    Table of Contents

    Learning Swift

    Credits

    About the Author

    About the Reviewer

    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

    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 on the console

    Control flow

    Conditionals

    Switches

    Loops

    Functions

    Basic functions

    Parameterized functions

    Functions that return values

    Functions with default arguments

    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 initializers

    Required initializers

    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 is scope defined

    Nested types

    Access control

    Summary

    4. To Be or Not to Be – Optionals

    Introducing optionals

    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

    The filter function

    The reduce function

    The map function

    The sorted function

    How these affect the state and nature of code

    Lazy evaluation

    Curried functions

    Summary

    6. Make Swift Work for You – Protocols and Generics

    Protocols

    Defining a protocol

    Implementing a protocol

    Using type aliases

    Defining a generic

    The generic function

    The generic type

    Type constraints

    Protocol constraints

    Where clauses for protocols

    Where clauses for equality

    Extending the existing generics

    Enhancing arrays

    Enhancing dictionaries

    Putting protocols and generics to use

    Generators

    Sequences

    Product of Fibonacci numbers under 50

    Summary

    7. Everything is Connected – Memory Management

    How data is stored in a computer

    Filesystem

    Memory

    Value types versus reference types

    Determining a value or reference type

    Behavior on assignment

    Behavior on input

    Capturing behavior of closure

    Automatic reference counting

    Object relationships

    Strong relationships

    Weak relationships

    Unowned relationships

    Strong reference cycles

    Strong reference cycles between objects

    Spotting

    Fixing the cycles

    With closures

    Spotting

    Fixing

    Lost objects

    Between objects

    With closures

    Summary

    8. Writing Code the Swift Way – Design Patterns and Techniques

    What is a design pattern?

    Behavioral patterns

    The iterator pattern

    The observer pattern

    The callback property

    The notification center

    Structural patterns

    The composite pattern

    Hierarchies

    An alternative to subclassing

    The delegate pattern

    Model-View-Controller

    Creational patterns

    A singleton/shared instance

    The abstract factory pattern

    Using associated values effectively

    Replacing class hierarchies

    Concisely representing a state

    Extending system types to reduce code

    Lazy properties

    Avoiding unnecessary memory usage

    Avoiding unnecessary processing

    Localizing logic to the concerned property

    Summary

    9. Harnessing the Past – Understanding and Translating Objective-C

    Swift's relationship with Objective-C

    The history of Objective-C

    Constants and variables

    Value types

    Reference types

    Containers

    Arrays

    Dictionaries

    Control flow

    Conditionals

    Switches

    Loops

    Functions

    Types

    Structures

    Enumerations

    Classes

    The basic class

    Initializers

    Properties

    Methods

    Inheritance

    Categories

    Protocols

    Blocks

    Projects

    Header files

    An implementation file

    Organization

    Calling Objective-C code from Swift

    A bridging header

    Using functions

    Using types

    Containers

    Reference type translation

    Summary

    10. A Whole New World – Developing an App

    Conceptualizing the app

    Features

    The 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

    11. What's Next? Resources, Advice, and Next Steps

    Apple's documentation

    Forums and blogs

    Blog posts

    Forums

    Prominent figures

    Podcasts

    Summary

    Index

    Learning Swift


    Learning 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: 1250615

    Published by Packt Publishing Ltd.

    Livery Place

    35 Livery Street

    Birmingham B3 2PB, UK.

    ISBN 978-1-78439-250-5

    www.packtpub.com

    Credits

    Author

    Andrew J Wagner

    Reviewers

    Giordano Scalzo

    Cory Bohon

    Commissioning Editor

    Sarah Crofton

    Acquisition Editors

    Vivek Anantharaman

    Richard Brookes-Bland

    Content Development Editor

    Kirti Patil

    Technical Editor

    Mrunmayee Patil

    Copy Editors

    Pranjali Chury

    Neha Vyas

    Project Coordinator

    Nidhi Joshi

    Proofreader

    Safis Editing

    Indexer

    Mariammal Chettiyar

    Graphics

    Disha Haria

    Production Coordinator

    Nilesh R. Mohite

    Cover Work

    Nilesh R. Mohite

    About the Author

    Andrew J Wagner is an independent software developer who concentrates on iOS development and backend web services and has a degree in computer engineering from Rensselaer Polytechnic Institute, New York. He has also been developing his own iOS apps through his company, Learn Brigade LLC, since 2008 and has experience working with and for large-scale companies and small-scale companies. He is passionate about using computers as a creative outlet and writing software that is beautiful in implementation, functionality, and experience.

    About the Reviewer

    Giordano Scalzo has been a developer since the days of the ZX Spectrum.

    He worked with C++, Java, .NET, Ruby, Python, and a ton of other languages he has forgotten the names of. After years of backend development and a hiatus from the technical side when he worked as a project manager, he is currently a freelancer in London where, through his company, Effective Code Ltd, he delivers code for iOS aiming at quality and reliability.

    In his spare time, when he is not crafting retro game clones for iOS, he writes his thoughts on his blog at http://giordanoscalzo.com.

    I'd like to thank my better half, Valentina, who lovingly supports me in everything I do—without you, none of this would have been possible.

    I would also like to thank my children, Mattia and Luca, who are my future and have given me lots of smiles and hugs when I needed them.

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

    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

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

    What this book covers

    Chapter 1, Introducing Swift, takes you through the process of installing Swift and running your first Swift program 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 to represent 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 more closely model the real world with code. It will teach you 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 to turn 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 them even more understandable and expressive code.

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

    Chapter 7, Everything is Connected – Memory Management, discusses 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. In this chapter, we dive deeper into the inner workings of Swift.

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

    Chapter 9, 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 you to make use of the vast resources that exist in Objective-C to help with your Swift development.

    Chapter 10, A Whole New World – Developing an App, explains the process of creating a real-world iOS application with the help of an example.

    Chapter 11, What's Next? Resources, Advice, and Next Steps, discusses how to move forward to become the best app developer you possibly can. It will also provide you with a list of resources you can use to continue your Swift and app development learning process.

    What you need for this book

    The only thing that you need for this book is Xcode 6.3.

    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. Learning Swift will place you in a small developer community that will explode in demand as the development of apps for Apple's platforms transitions to it. You will find this book especially useful if you are new to programming or if you are yet to develop an app 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.

    Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: It stores the text Something Else into a new variable called str.

    A block of code is set 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: To view the console, you can go to View | Assistant Editor | Assistant Editor.

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

    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

    A programming language is really only ever a means to an end, and you are not going to learn much from this book or any other resource if you don't have at least some idea of what that end is. Before diving into learning Swift, we have to understand what it really is and how it will help us achieve 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 this, we will go over the following topics:

    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 to allow developers to continue pushing their platforms forward. It is their attempt to make iOS and OS X app development more modern, safe, and powerful.

    Developers have already begun looking for ways to push Swift to do even more than iOS and OS X app development. Some are using it to create command-line scripts to replace/supplement the existing scripting languages, such as Python and Ruby. However, Apple's priority, at least for now, is to make it the best language possible to facilitate app development.

    It is important to note that learning Swift is only the first step towards developing Apple's platforms. To develop a device, you must learn the programming language and the frameworks that the device maker provides. Skill in a programming language is the foundation to get 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, first, you need to step away from the table and focus on developing your skill set. The better you are at using the tools, the more possibilities open up to you to create more advanced and high quality furniture. Similarly, with 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 language-related skill set. 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 wouldn'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 with Swift. To do this, we will introduce the syntax and features of Swift in a practical way. You will build up a rich toolset, and see it being 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 have a Mac running OS X. The only piece of software you will need is called Xcode (version 6 and higher). This is the environment that Apple provides to facilitate 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.

    Tip

    Downloading the example code

    You can download the example code files for all Packt books you have purchased 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.

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

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

    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 along the right-hand side of the sidebar.

    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 to add extra information about your code there inline with it. In Swift there are two types of comments: single line and multiline. Single line comments such as the one in the previous code always start with //. 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

    */

    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 the last 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 be updated, 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.

    Another 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 Swift code is completely valid. 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 are shown the full error:

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

    Now the results are shown in black again and we can see that they have been updated for the latest code. If you have experience with other programming environments, the reactiveness of the playground may surprise you. Let's take a peek under the

    Enjoying the preview?
    Page 1 of 1