Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Learning Swift
Learning Swift

Learning Swift: Build a solid foundation in Swift to develop smart and robust iOS and OS X applications

Arrow left icon
Profile Icon Andrew J Wagner
Arrow right icon
zł39.99 zł158.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.8 (5 Ratings)
eBook Jun 2015 266 pages 1st Edition
eBook
zł39.99 zł158.99
Paperback
zł197.99
Subscription
Free Trial
Arrow left icon
Profile Icon Andrew J Wagner
Arrow right icon
zł39.99 zł158.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.8 (5 Ratings)
eBook Jun 2015 266 pages 1st Edition
eBook
zł39.99 zł158.99
Paperback
zł197.99
Subscription
Free Trial
eBook
zł39.99 zł158.99
Paperback
zł197.99
Subscription
Free Trial

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Learning Swift

Chapter 2. Building Blocks – Variables, Collections, and Flow Control

One of the coolest things about programming is the way its concepts build on each other. If you've never programmed anything before, even the most basic app can seem very complex. The reality is that if you analyze everything going on in an app down to the ones and zeroes flowing through the processor, it is incredibly complex. However, every aspect of using a computer is an abstraction. When you use an app, the complexity of the programming is abstracted away for you. Learning to program is just a way of going one level deeper to make a computer work for you.

As you learn the basic concepts behind programming, they will become your second nature and this will free your mind to comprehend even more complex concepts. Just as when you first learn to read, sounding out each word is challenging. However, at some point, you reach a level where you glance at a word and you know the meaning instantaneously...

Core Swift types

Every programming language needs the ability to name a piece of information to be referenced later. This is the fundamental way that a collection of code remains readable after it is written. Swift provides a number of core types that help you represent your information in a very comprehensible way.

Constants and variables

Swift provides two types of information: a constant and a variable:

// Constant
let pi = 3.14
   
// Variable
var name = "Sarah"

All constants are defined using the let keyword followed by a name, and all variables are defined using the var keyword. Both the constants and variables in Swift must contain a value before they are used. This means that when you define a new constant or variable, you will most likely give it an initial value. You do so using the assignment operator (=) followed by a value.

The only difference between the two is that a constant can never be changed, while a variable can be. In the previous example, the code defines a...

Swift's type system

Swift is a strongly typed language, which means that every constant and variable is defined with a specific type. Only values of a matching type can be assigned to them. So far, we have been taking advantage of a feature of Swift called type inference. This makes it such that the code does not have to explicitly declare a type if it can be inferred from the value assigned to it during declaration.

Without the type inference, the name variable declaration from before would be written as:

var name: String = "Sarah"

This code explicitly declares name as the type String with the value "Sarah". A constant or variable's type can be specified by adding a colon (:) and a type after its name.

A String type is defined by a series of characters. This is perfect for storing text like our name example. The reason that we don't actually need to specify the type is that "Sarah" is a String literal. The text surrounded by quotation marks is a...

Printing on the console

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

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

println("Hello World!")

If you put that code into a playground, you will see "Hello World!" written in the results pane. However, this is not truly the console. To view the console, you can go to View | Assistant Editor | Assistant Editor. A new view will appear to the right of the results pane and it will have a section called Console...

Control flow

A program wouldn't be very useful if it were a single fixed list of commands that always did the same thing. With a single code path, a calculator app would only be able to perform one operation. To make an app more powerful, there are a number of ways in which we can use the data to make decisions as to what to do next.

Conditionals

The most basic way to control the flow of a program is to specify certain code that should only be executed if a certain condition is met. In Swift, we do that with an if statement. Let's look at an example:

if invitees.count > 20 {
   println("Too many people invited")
}

Semantically, the preceding code reads, "If the number of invitees is greater than 20, print Too many people invited. This example only executes one line of code if the condition is true, but you can put as much code as you like within the curly brackets ({}).

Anything that can be evaluated as either true or false can be used in an if statement. You can...

Functions

All of the code we have explored so far is very linear down the file. Each line is processed one at a time and then, the program moves onto the next. This is one of the great things about programming: everything the program does can be predicted by mentally stepping through the program yourself, one line at a time.

However, as your program gets larger, you will notice that there are many places that reuse very similar or identical code that you cannot reuse using loops. Also, the more code you write, the harder it will become to reason in your head about what it is doing. Code comments can help with that, but there is an even better solution to both of these problems and they're called functions. A function is essentially a named collection of code that can be executed and reused by name.

There are various types of functions but each builds on the previous type.

Basic functions

The most basic type of function simply has a name with some static code to be executed later. Let&apos...

Core Swift types


Every programming language needs the ability to name a piece of information to be referenced later. This is the fundamental way that a collection of code remains readable after it is written. Swift provides a number of core types that help you represent your information in a very comprehensible way.

Constants and variables

Swift provides two types of information: a constant and a variable:

// Constant
let pi = 3.14
   
// Variable
var name = "Sarah"

All constants are defined using the let keyword followed by a name, and all variables are defined using the var keyword. Both the constants and variables in Swift must contain a value before they are used. This means that when you define a new constant or variable, you will most likely give it an initial value. You do so using the assignment operator (=) followed by a value.

The only difference between the two is that a constant can never be changed, while a variable can be. In the previous example, the code defines a constant called...

Swift's type system


Swift is a strongly typed language, which means that every constant and variable is defined with a specific type. Only values of a matching type can be assigned to them. So far, we have been taking advantage of a feature of Swift called type inference. This makes it such that the code does not have to explicitly declare a type if it can be inferred from the value assigned to it during declaration.

Without the type inference, the name variable declaration from before would be written as:

var name: String = "Sarah"

This code explicitly declares name as the type String with the value "Sarah". A constant or variable's type can be specified by adding a colon (:) and a type after its name.

A String type is defined by a series of characters. This is perfect for storing text like our name example. The reason that we don't actually need to specify the type is that "Sarah" is a String literal. The text surrounded by quotation marks is a String literal and is inferred to be of the type...

Left arrow icon Right arrow icon

Description

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.

Who is this book 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.

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jun 30, 2015
Length: 266 pages
Edition : 1st
Language : English
ISBN-13 : 9781784399627
Vendor :
Apple
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jun 30, 2015
Length: 266 pages
Edition : 1st
Language : English
ISBN-13 : 9781784399627
Vendor :
Apple
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just zł20 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just zł20 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 597.97
Mastering Swift
zł221.99
Learning Swift
zł197.99
Swift By Example
zł177.99
Total 597.97 Stars icon
Banner background image

Table of Contents

12 Chapters
1. Introducing Swift Chevron down icon Chevron up icon
2. Building Blocks – Variables, Collections, and Flow Control Chevron down icon Chevron up icon
3. One Piece at a Time – Types, Scopes, and Projects Chevron down icon Chevron up icon
4. To Be or Not to Be – Optionals Chevron down icon Chevron up icon
5. A Modern Paradigm – Closures and Functional Programming Chevron down icon Chevron up icon
6. Make Swift Work for You – Protocols and Generics Chevron down icon Chevron up icon
7. Everything is Connected – Memory Management Chevron down icon Chevron up icon
8. Writing Code the Swift Way – Design Patterns and Techniques Chevron down icon Chevron up icon
9. Harnessing the Past – Understanding and Translating Objective-C Chevron down icon Chevron up icon
10. A Whole New World – Developing an App Chevron down icon Chevron up icon
11. What's Next? Resources, Advice, and Next Steps Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.8
(5 Ratings)
5 star 80%
4 star 20%
3 star 0%
2 star 0%
1 star 0%
Ronnie Pitman Aug 16, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is not a huge, thick book, but it is a book packed with information. In the Preface it is written that this book is “especially useful if you are new to programming or….” While it’s true that Chapter 2 does start with the basics—variables, constants, tuples, arrays, dictionaries, etc.—the material moves on quickly. All concepts, throughout the book, are amply demonstrated in Playgrounds, but still, someone new to programming will have to pay close attention and probably reread portions. In at least two chapter summaries, the author himself refers to the material presented as having been dense. It’s good to have a book that deals in depth.Many programming books teach Swift in the context of iOS. This one does not but instead concentrates on Swift language fundamentals. It’s not a tutorial on how to build this or that app, and only in the penultimate chapter does the author address iOS and building an app.Many programming books also jam a great deal of code into one class. This author places a premium on code reuse and flexibility and writes his code accordingly.A note on the book’s code files: at the time I write this, if you download them from the publisher website they download as Learning Swift.zip.html. Unless Packt knows something I don’t know, you have to strip .html off the file name for it to open as a zip file rather than as gibberish.A small error in Chapter 2 (pdf page 13): “View | Assistant Editor | Assistant Editor” should be “View | Assistant Editor | Show Assistant Editor”. Otherwise this book is admirably edited and proofread.
Amazon Verified review Amazon
Aurélien Sep 02, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
What this book is not:This book is not a Bible, it does not deal with countless topics, it is not either a how-to guide to programming your first Iphone app. "Learning Swift" is not packed with information easily googled and deprecated within the next 6 months.What it is:Instead "Learning Swift" focuses on how to understand Swift programming, how the language is structured and how it works.It gives the keys to become a good swift developper by understanding the core concepts, while being concrete at every step of the process.A whole chapter is dedicated to Design Patterns, and even chapter 10 "Developing an App" is full of good advices on how to code properly and how to refactor your code.
Amazon Verified review Amazon
Winston Sep 05, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The author does a great job of taking the reader through all the intricacies of the swift programing language. Apple is now in Swift 2 and this book will put any novice or experienced developer in the drivers seat to building award winning ios apps. Buy it!
Amazon Verified review Amazon
Sergio Martinez-Losa del Rincon Aug 14, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is a very nice one to learn swift from scratch, it is useful information from easy topic to difficult ones, you can learn many useful thinks like categories, interpolation, infix/postfix, optionals...Patterns chapter is very handy, because you can reuse your programming techniques to create a more easy code. Also I found very useful optionals information.I learn a lot with this book, it deserves a 5-stars.
Amazon Verified review Amazon
Michael Aug 28, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
I am new to learning Mac and iOS programming. This book is great even though I've only gotten through a couple chapters. It starts out with the basics of types, collections, conditionals and loops and builds on that.One note, this book was written for XCode 6 and Swift 1.2 so it will hopefully be updated for XCode 7 and Swift 2 when they are released since some of the basic functions are changing, for example the println() function is replaced by print(). The beta for XCode 7 does have functionality to convert the 1.2 to 2.0 code. Hopefully that will be in the final build of XCode 7.I look forward to getting deeper into learning Swift.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.