Learn Swift Programming by Examples Sample
Learn Swift Programming by Examples Sample
Learn Swift Programming by Examples Sample
Zhimin Zhan
This book is for sale at http://leanpub.com/learn-swift-programming-by-examples
This is a Leanpub book. Leanpub empowers authors and publishers with the Lean
Publishing process. Lean Publishing is the act of publishing an in-progress ebook using
lightweight tools and many iterations to get reader feedback, pivot until you have the right
book and build traction once you do.
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i
What is unique about this book? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ii
Who should read this book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iii
How to read this book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iii
Send me feedback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iii
1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1 Xcode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Swift Playgrounds in Xcode . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Swift Projects in Xcode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4 Swift Tutorials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.5 Rhythm for working on the exercises . . . . . . . . . . . . . . . . . . . . . . 6
1.6 Common Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.7 Interactive Swift . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.8 Swift evolves . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2. Printing Shapes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.1 Print out Triangle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.2 Print out a half diamond . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.3 Print out diamond shape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.4 Print big diamond, name your size . . . . . . . . . . . . . . . . . . . . . . . . 20
2.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Online resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Books . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Preface
On December 8, 2013, US President Barack Obama “asked every American to give it a shot
to learn to code” (watch it here¹), kicking off the Hour of Code campaign for Computer
Science Education Week 2013. “Learning these skills isn’t just important for your future, it’s
important for our country’s future,” President Obama said.
In February 2013, Mark Zuckerberg and Bill Gates and several other big names in IT “want
kids to learn code” (video²). I particularly like the quote at the beginning of the video:
You don’t have to be an American to get the message: coding (aka. programming) is an
important skill for this information age. Besides the importance of programming, the other
message those VIPs also tried to convey is that “you can do it”.
Learning programming is a way to master communication with computers, by giving them
instructions to perform tasks for you. A programming language is a language that is used
to write instructions for computers to understand and execute. There are several popular
programming languages such as Java, C#, Ruby, and PHP. For beginners, don’t fixate on
one. Computers internally work the same way, mastering thinking in programming is more
important than an individual language. In my opinion, different programming languages are
like dialects. I learned and taught myself over a dozen of programming languages. Once you
have mastered one, it is easy to learn another.
In this book, I will use Swift, a new programming language from Mac OS X and iOS. Swift
was first unveiled at the Apple Worldwide Developers Conference (WWDC) 2014, Apple
describes Swift as “a successor to both the C and Objective-C languages”³ on its website.
Before Swift, Objective-C was the only programming language you could use to build Mac
and iOS apps. Redmonk programming language rankings for 2015⁴ shows a huge growth
¹https://www.adafruit.com/blog/2013/12/09/president-obama-calls-on-every-american-to-learn-code/
²http://www.psfk.com/2013/02/mark-zuckerberg-bill-gates-coding-school.html
³https://developer.apple.com/swift
⁴http://redmonk.com/sogrady/2015/01/14/language-rankings-1-15/
Preface ii
in popularity for Apple’s new Swift development language. According to the results, Swift
went from the 68th most popular language last quarter (when it launched) to the 22nd, a
jump of 46 spots which is “unprecedented in the history of these rankings.”
In June 8, 2015 at WWDC 2015, Apple announced that the company is open-sourcing the
Swift 2.0⁵. “We think Swift is the next big programming language, the one that we’ll all be
doing application and system programming on for 20 years to come,” Craig Federighi, Apple’s
senior vice president of software engineering, said. “We think Swift should be everywhere
and used by everyone.”
What do these mean? Swift will be the main programming (replacing Objective-C) for coding
applications for Apple’s iOS, Mac OS and tvOS platforms, and developers like it. A good news
for beginners, comparing to Objective-C, Swift is a lot easier to learn. So learn and master
Swift, as President Obama said in the video, “Don’t just download the latest app, help design
it; Don’t just play on your phone, program it”.
In this book, I have chosen the exercises that are very simple to understand, besides teaching
values, they are useful and fun to do.
There are also some programming quiz books. I often find some of those exercises are long
and hard to understand. Quite commonly, the authors seem to be fond of showing off their
programming skills or smart solutions. It won’t be the case in this book. This book is a guide
to programming and its purpose is to teach. After you finish all the exercises, you will be
able to write working (might not be perfect) programs, and with confidence to continue to
learn and grow.
Send me feedback
We’d appreciate your comments, suggestions, reports on errors in the book and code. You
may submit your feedback on the book site.
Zhimin Zhan
Brisbane, Australia
⁷http://zhimin.com/books/learn-swift-programming-by-examples
1. Introduction
I still remember my first programming lesson. The first sentence the coach said was
“computers are not mysterious”. Nobody uses the term ‘mysterious’ to describe computers
nowadays. It was the case in 1980’s, computers were rare back then.
We are in the “Information Age” now, where computers are a large part of our lives. It seems
to me that programming remains mysterious and difficult to the majority of people despite
the fact that they spend most of their work hours in front of computers.
Once you have mastered programming, there are many things you can do, such as:
The bottom line is that when you know how software works you will definitely use
computers better.
Before we start, just like my coach, I am telling you that “programming is not mysterious”,
and you can master it. I believe this book can guide you to the wonderful programming
world.
Like many skills, you cannot master programming by reading the book only, you need to do
it. Let’s begin.
1.1 Xcode
Coding Swift requires Xcode 6 or later installed on a Mac computer. Xcode is the integrated
development environment (IDE) for developing software for OS X and iOS. Xcode¹ (the latest
version to date is 8.0) is available free of charge on the Mac App Store.
¹https://developer.apple.com/xcode/downloads/
Introduction 2
The code in on the left and evaluated output on the right (in a slight darker back-
ground).
You are ready to go, type in some Swift code. Xcode supports IntelliSense, i.e. providing code
competition and code suggestions.
In Xcode Playground, the output of each statement will be shown on the right pane (gray
one). To display the whole program’s output, which is always a good idea, show the Debug
area as below.
Introduction 4
More commonly, we organize code and related files in a folder structure, known as “Project”.
When we a Xcode project file (with extension .xcodeproj) in Xcode, all the files in the project
are included.
4. Project created
Introduction 6
Now write the code for the exercise. No one can learn programming by reading, you have
to actually do it. You may refer to the hints section to to help you get through.
• Hints
Techniques and short executable code that may help you to solve the problem when
you get stuck.
• Solution(s)
Solutions (can be found at Appendix II) to the most of exercises are between 20 to 50
lines of code. The runnable solution scripts can be downloaded at the book site.
If you are struggling to solve an exercise, feel free to check out our solutions (at
Appendix II). The exercises are selected to introduce new programming skills/practices
as well as previous knowledge. Don’t worry if you cannot get it right the first time,
you will have chances to apply in later exercises. As long as you are trying, you are
learning.
• Review
Think about what you have learned, look at the code you just wrote, try apply new-
learnt skills to solve similar problems.
Typos
It is normal that we make typing mistakes when writing code. Xcode checks the syntax of
code before running it. If there are syntax errors in code, the error messages are usually
quite helpful for identifying the error. For example, in the code below, line 10 has a typo
elwe instead of else.
The error message means elwe is undefined (don’t worry if it is not meaningful to you yet,
you will understand soon). It helps identify where the error is.
Just like Math, if there is a left bracket “(“ in code, there shall be a matching right bracket “)”.
There are also matching keywords for certain code structures, such as if { … }. For example,
there are two errors in the code below.
The above two kinds of errors (called syntax errors) are relatively easy to spot, as highlighted
in Xcode. The difficult errors for programmers are code logic errors. That is, the code can
run without syntax errors, but does not behave as it is supposed to. The ability to debug code
errors (find and fix them) separates good programmers from the average. With practice, you
will get better on this.
For beginners, I have some practical tips.
Open terminal
The best way to interact with your programs is from the command line, you might have
seen these scenes in some Hollywood movies: hackers typed some commands in some
text windows, and something (usually big) happened. That windows that accept user text
commands are called terminals.
The application to access the command line in Mac OS X is called ‘Terminal’. Open in Finder:
‘Applications” → ‘Utilities” → ‘Terminal’.
The Swift version might be different on your machine, this won’t matter.
$ cd swiftcode
$ swift hello_world.swift
( cd means ‘change directory’; swift filename means running this swift file.)
You will see the output:
Hello World!
$ swift
Welcome to Apple Swift version 5.1 (swiftlang-1100.0.270.13 clang-1100.0.33.7).
1> print("Hello " + "Swift")
Hello Swift
2>
For example, the common print method, which prints out text to console, has changed three
times from 1.0 to 2.0.
print("Hello") // Swift 1
print("Hello", appendNewline: false) // Swift 1.2
print("Hello", terminator: "") // Swift 2
2. Printing Shapes
Printing out asterisk characters (*) in shapes is often used as beginner’s programming
exercises, as they are simple, easy to understand and visually interesting.
*
**
***
****
*****
******
*******
********
*********
**********
Purpose
Analyze
Printing Shapes 13
Hints
print("*")
print("**") // will be in a separate line
Variables
You can think of a variable is a ‘labeled box’ in computers to store data, its data
can be changed. The syntax convention¹ for Swift variables is lower Camel Case²,
for example, myBirthDate.
¹https://github.com/raywenderlich/swift-style-guide
²http://c2.com/cgi/wiki?LowerCamelCase
Printing Shapes 14
var starCount = 2
print(String(repeating: "*", count: starCount)) // => '**'
Output:
1
2
3
The { … } mark the beginning and end of loop respectively. The variable index is the looping
index, often used in the code within the loop. print(index) is the code fragment that executes
for specified 3 times.
*
**
***
****
*****
******
*******
********
*******
******
*****
****
***
**
*
Purpose
• Decrement count in loops
Analyze
The key to this problem is to determine the number of stars for the corresponding rows.
Hints
Control flows using if … else
Code, in its simplest form, is executed from top to bottom. But if there are if conditions and
loops (and later methods and classes), it will change the flow of execution. The conditional
expressions (if-then-else statements) run different code statements depending on a boolean
condition (true or false).
Printing Shapes 16
var score = 75
if score < 60 {
print("Failed!")
} else {
print("Pass!")
}
Output:
Pass!
If you change the var score = 59 and run again, you will get Failed!.
Boolean condition
The statement score < 60 after if is called a boolean condition. Its value can only be either
true or false (which are called boolean values).
== equal to
!= not equal to
< less than
<= less than or equal to
> greater than
>= greater than or equal to
Examples:
Please note the “assignment operator” is different from the “equality symbol” in
Math. For example, the statement below increases the value of a by 1 (assign a
new value to a) in programming code. The same equation in Math is invalid.
a = a + 1 // increment a by 1
The double equal signs (==) is a comparison operator, it compares two values for
equality (returns true if a is equal to b, false otherwise).
if a == b {
print("Found a match!")
}
³http://www.cprogramming.com/tutorial/common.html
Printing Shapes 18
*
***
*****
*******
*****
***
*
Purpose
Analyze
Below are formulas to calculate the number of star; where rowNumber represents the row
number and totalRows represents the total number of rows,
1. The number of stars for the rows before the middle one is (rowNumber - 1) * 2 + 1.
2. the number of stars for the rows after the middle one is (totalRows - rowNumber) * 2
+ 1
Think about the spaces in front of each row, except for the 4th row (the longest middle one).
Hints
Write down the number of spaces and stars for each row.
Printing Shapes 19
8 / 2 // => 4
9 / 2 // => 4, ignore the remainder
(1 + 2) * 3 + 3 / 2 // => 10
If you have difficulty, do it step by step. You may try to print out the top triangle
first.
Printing Shapes 20
Purpose
Analyze
The size of the diamond is not fixed, it depends on the number the user entered. The number
the program asks the user to enter is the total number of rows, which can be stored in an
variable.
If you divide the diamond into two parts (top and bottom), work out the number of rows for
each part.
Hints
Read user’s input
We can use readLine() function to read user’s input from a command line application.
let userInput = readLine()
var c = 12
var d = 3
c + d // => 15
Math operations, such as Add, between String and Integer will get compile error.
var b = "3"
var c = 12
b + c // Binary operator '+' cannot be applied to 'String' and 'Int'
**
Swift Optionals
Optionals in Swift is quite difficult concept for me, as it is not in other languages I have used.
The purpose of Optionals is to avoid assign nil (means no value) to a variable. It is better
explained with example.
Printing Shapes 22
var str1:String
str1 = nil // error: Nil cannot be assigned to type "string"
var str2:String?
str2 = nil // OK
However, you can force assigning an optional variable to non-optional one by using !.
var str3:String
str3 = str2 // error: Value of optional type "String?" not unwrapped
str3 = str2! // OK
You might still find it confusing. Good news is that Xcode will give you hints and even offer
‘Fix it’.
2.5 Exercises
Write code to print out the shapes below, the width of shape is changeable.
Rhombus
*****
*****
*****
*****
*****
Hollow Square
*****
* *
* *
* *
*****
Heart
***** *****
******* *******
********* *********
*******************
*****************
***************
*************
***********
*********
*******
*****
***
*
Hints
Online resources
• The Swift Programming Language Guide and Reference⁵
The official Swift language guide.
• Raywenderlich Tutorials⁶
Good quality tutorials on Swift and App development.
Books
• The Swift Programming Language⁷
The official Swift ebook from Apple.
• Learn Ruby Programming by Examples⁸ by Zhimin Zhan and Courtney Zhan
Learn Ruby programming to empower you to write scripts and cool web applications
(Ruby on Rails). Master Ruby quickly by leveraging this book.
• Cocoa Programming for OS X⁹ by Aaron Hillegass, Adam Preble and Nate Chandler,
Big Nerd Ranch
A good book on Cocoa programming.
⁴http://zhimin.com/books/learn-swift-programming-by-examples
⁵https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/
⁶http://www.raywenderlich.com/tutorials
⁷https://itunes.apple.com/au/book/swift-programming-language/id881256329?mt=11
⁸https://leanpub.com/learn-ruby-programming-by-examples-en
⁹https://www.bignerdranch.com/we-write/cocoa-programming/
Resources 25
Software
• CocoaPods¹⁰
CocoaPods is a long-standing dependency manager for Cocoa.
• Carthage¹¹
Alternative to CocoaPods, a simpler dependency manager.
¹⁰https://cocoapods.org/
¹¹https://github.com/Carthage/Carthage