Swift 2 Quick Start
Recently, Apple has open sourced their own programming language, Swift, which is currently on version 2.1. Just after a few days of their release in GitHub, it became the most popular open source programming language. Apple, with contributors worldwide, is continuously developing and improving Swift, thus the more reason for us to start learning Swift. Apple’s vision for Swift really is for people to use Swift in all kinds of cases such as web development as well. So, let’s start learning Swift.
This tutorial is for experienced programmers. If you’re beginning to learn programming, the best way to learn with Swift is by reading Apple’s official book, The Swift Programming Language, the official documentation for Swift.
I suggest you use an Xcode Playground to follow this tutorial since it displays the contents of the variables as you write your code without needing to compile your code.
The simplest program you can make, as with most programming languages, is a Hello World program. To print out a
String, you can simply use the
print("Hello World!"). That’s it. No import statements, namespace, prefixes, main function, etc. Also note that Swift doesn’t require you to put semi-colons at the end of one-line statements, so you can type code faster and get less errors when compiling. Although, you have to put semi-colons if you decide to write more than one statement in a single line (Why would you??)
Variables and Constants
Now that you now how to print output, let’s move on with variables and constants. In Swift, we declare variables with the
var keyword. On the other hand, if you want a constant, you have to use
let. The main difference between a variable and a constant is that with constants, you can’t change it’s value once you’ve assigned it one.
To print out values of numbers or other types, you can simply use string interpolation,
"The value of pi is \(pi)".
As you’ve noticed from the example above, we did not need to explicitly state the type of the variable or constant at declaration. Swift automatically infers the type of the variable from the value you assign to it. So if you assign
10 to a variable,
var anInteger = 10 , the variable is an integer type, or an
Int. In the examples above,
pi has an inferred type of
completed of type
Bool. Once a variable is assigned a type, it can never change its type, so, you can’t assign
We can also explicitly state the type of a variable we declare:
doubleValue is of type double with a value
10.0. These are some of the basic types for Swift:
Lastly, you can create
Arrays using brackets around a type, such as
[Int] for creating an array of integers.
Casting to other types is simple in Swift. The basic types of Swift are structs, so most of them also provide initializers for other type such as:
Another unique feature of Swift are the use of Optional types. Optional types are types that can either have some value or none (
null in other programming languages). Optionals can be applied to all types, such as
String. To indicate if a type is an optional, we simply append a
? at the end of the type:
Int? as an optional integer, and
String? as an optional integer.
Take note that since an optional integer (
Int?) is different to an integer (
Int), you can’t assign an optional to a non-optional (
Int). In order to assign the value of an optional, if it has a value, you have to unwrap the optional first. The simplest way to unwrap is through the usage of the force unwrap operator
However, most of the time, FORCE UNWRAPPING IS A BAD IDEA. Try the same code above, but with
nil assigned to
someValue. The result is an error, specifically a runtime error - the code would compile, and the program will run, but the program will crash once the program tries to force unwrap an empty optional. In short, your app will crash. So, you might think that to prevent force unwrapping an empty optional, you will check if it’s not nil first. Yes, that will be safer, and prevent your program from crashing. Although, Swift provides a better way for safely unwrapping an optional, which is called optional binding.
Swift mostly has the same operators with other languages, such as
% for basic operations.
+ also supports
Arrays. Swift also has shorthand operators for arithmetics:
a += b is the same with
a = a + b.
Swift also has the basic comparison operators,
!. Take note that
! for NOT is different from the
! for force unwrapping optionals.
! for NOT is a prefix, while
! for unwrapping is a suffix.
As you’ve seen from the example above in optional binding, Swift also has
if-else statements. Swift, as with other modern languages, doesn’t require parenthesis in conditions.
Swift also has a
switch statement. However, unlike other languages, it doesn’t require you to put
breaks on every case, which is good since you rarely have to fall-through cases. Though, if you ever need to fall-through, you can always use the
The most basic loop you can do in Swift is to iterate through a range, for example, from 0 to 9, using the
Of course, you can also do this with C-style loops with iterators:
Note that Apple will remove this C-style loop in Swift 3.0. So if you ever need to iterate through a loop with different increment magnitude, you can always use the
stride method of numbers.
The next basic loop is the
while loop, which is pretty much the same with most languages.
Usually paired with the
while loop is the
do-while loop. In Swift, they call use
repeat-while instead for a more readable language.
Functions with Swift are declared with the
func keyword, followed by the function name, and a parenthesis containing the parameters if any. To indicate the function returns something, use
-> Type after the parenthesis where Type is the return type.
Functions in Swift have named parameters after the first parameter. By default, the parameter name is the same as the parameter’s variable name. To change this, you can type in the name of the parameter before the variable name (to make the function more readable if necessary). You can also type in a parameter name for the first parameter to require a parameter name for it.
You can also remove the parameter name by using underscore, _ , in place of it.
So that’s it for a quick start of Swift. I hope this tutorial helped you get started with Swift, or at least encourage you to learn Swift. There are still lots of topic I did not cover, such as tuples, Classes, Structs, Enums, etc. There’s also an interesting feature for pattern matching in Swift:
If that doesn’t interest you enough, skim through the The Swift Programming Language ebook to look for more advanced and cool stuff in Swift. If you want to see some examples of Swift code, I got some open source libraries and apps in GitHub. All of my apps in the App Store are also built using Swift.