Show Menu

Swift 4 Cheat Sheet (DRAFT) by

Apple Swift 4 Complete Reference

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Variable declar­ations

let variable [: type] = value
Define a constant, providing a type.
let variable [: type] = value
Defina a variable, providing a type.
Swift inferes types based on the type of contents that is assigned at creation time. The type declar­ation is optional.


/* This is a multiline comment in Swift */
// This is a single line comment in Swift
Comments may be either single or multiline and may even be written after the last command on a line.

Data types

Default Integer value depending on the running platform
1 Byte =
-127...+127 (signed)
4 Byte =
-2 147 483 648...+2 147 483 648
8 Byte =
-9 223 372 036 854 775 808...
+9 223 372 036 854 775 808
( ~6 digits precision )
( ~15 digits precision )
Can be either true or false.
Only one character in length.
Same as character but unlimited in length
Can be either a value (of any type) or no value.
All Int values may be preceded by a capital U to indicate an unsigned range, which shifts min values to 0 and max values to their double.


var myInt = 10
Normal, decimal notation
var myInt = 0xa
Hexade­cimal notation of 10
var myInt = 0b1001
Binary notation of number 10
var myInt = 0o11
Octal notation of number 10
Floating Point
var myFloat = 12.345
Normal, decimal number notation.
var myFloat = 1.2345e1
Expone­ntial notation of the above number.
var myFloat = 
Hexade­cimal double (which I honestly don't use)
All characters should be enclosed in double quotes. We may use the following escape sequences to escape special charac­ters.
NULL Character
Backslash character
Carriage Return
Horizontal Tab
Vertical Tab
Double Quote
Single Quote
Character repres­ented by Octal number 55
Character repres­ented by Hex-Number 99
Value is true
Value is false
There is no value


Optionals is actually a new datatype within Swift. As the use and unders­tanding of optionals are of utmost import­ance, let's have a look at them in depth.
var myInt : Int?
means that the variable named myInt could contain an integer value but does not have to.
If it does contain a value it will be of type Some(Type), if it doesn't it will be None
in the code, means that the programmer will make sure that myInt contains a value of type Some(T). This is called Forced Unwrapping.
var myInt : Int!
allows a normal use (i.e. the use without ? nor !) of the variable in our code. This is called Automatic Unwrapping.
To check if an optional contains an actual value or not, we use a code block like this one:
if myInt != nil { //code } else { //code }
Another technique is called Optional Binding, and allows to check for a value directly during declar­ation of the variable:
if let myInt = myUnce­rta­inInt { //code } else { //code }


a * b
Multiply a by b.
a / b
Divide a by b.
a % b
Modulus ( remainder after / )
a + b
Add a to b.
a - b
Substract a from b.
Pre or post increment.
Pre or post decrement.
a == b
A is equal to b.
a != b
A is not equal to b.
a > b
A is greater than b.
a < b
A is less than b.
a >= b
A is greater or equal to b.
a <= b
A is less or equal to b.
 a && b
Is true while a and b are true.
a || b
Is true while a or b are true.
a ! b
Is true while only one of a or b is true.
Bitwise and.
Bitwise or.
Bitwise xor.
Bitwise ones complement.
Bitwise shl.
Bitwise shr
a = b
Assign b to a.
a += b
Assign a+b to a.
a -= b
Assign a-b to a.
a *= b
Assign a*b to a.
a /= b
Assign a/b to a.
a %= b
Assign a%b to a.
a <<= b
Assign a shl b to a.
a >>= b
Assign a shr b to a.
a &= b
Assign a and b to a.
a ^= b
Assign a xor b to a.
a |= b
Assign a or b to a.
( 1..4 )
Closed range, i.e. 1,2,3,4.
( 1..<4 )
Half open range, i.e. 1,2,3.
( a==b ) ? x : y
Ternary operator.
If a is equal to b then return x, if not return y.


var myString = ""

var myString = String()
Both create an empty string.
var myString = "­one­"

myString += " two"
Concat­enates two strings, and returns "one two".
var myString = "one " + "­two­"
Another wat to concat­enate two strings.
var myName = "Tony"

var myGreeting = "Hello \(myName)"
This inserts a string into another string. Note that this is not limited to strings, but also works with numbers.
var myAge = 18

var myGreeting = "Age: \(myAge)"

String relevant functions and methods

Returns true if empty and false if not.
var myString = "two words"
Returns "Two Words"
Returns "two words"
(this appears to be no change, but in fact, all characters are converted to lowercase.
Returns "TWO WORDS"
count( myString )
Returns 9
Consult: Docs for further inform­ation.


var myArray:Array<Type> = Array()
This creates an empty array.
var myArray:[Type] = []
Shorthand method to create an array with values X, Y and Z
var myArray = [Type]()
This is the shortest of the shorthands available.
var myArray = Array(repeating: X, count: X)
This allows to create an array with a default value and a given size.
Returns the first element of the array.
Multi-­Dim­ens­ional Arrays
var myArray:Array<Array<Type>> = Array(Array())
Same as above, but multi-­dim­ens­ion­ally.
var myArray:[[Type]] = [[]]
var myArray = [[Type]]()

Array relevant functions and methods

Returns the number of items go an array.
Returns true if it is empty and false if not.
Returns first element of array
Returns last element of array
Appends an element to an array (there are variations to this)
myArray.insert(value at:X)
Inserts value at position X
myArray.remove(at: X)
Removes the element at position X
myArray.index(of: value)
Returns the index (i.e. position) of value inside the array.
Consult: Docs for further inform­ation.


var myDict: [Type:Type] = [:]
This creates an empty dictio­nary.
var myDict = [key:value]
Creates a dictionary with given key:value pairs.
for (key, value) in myDict { 
Iterate over a dictionary accessing key:value pairs in each iteration.

Dictio­naries relevant functions and methods

Returns the amount of data pairs available.­Empty
Returns true if the dictionary is empty.
myDict.up­dat­eValue(value, forKey: key)
Updates a value inside the dictio­nary.­dex­(fo­rKey: key)
Returns the index where given key is located.­mov­eVa­lue­(fo­rKey: key)
Removes a key:value pair.
Consult: Docs for further inform­ation.

Flow control (Decision making)

if a==b {
} else {
If a is equal to b, the first block of code is executed. If not, then the last block of code is executed. The else block may be present or not.
switch variable { 
 case 1:
 case 2:
 case 3:
  //code 3
  //code default
The switch statement checks a variable for a given value. No break statement is needed. If we want a fallth­rough to happen, we need to specify this in the code block. In this example, case 2 always gets executed together with case 3. The default statement catches all non matching cases.
Ternary oprerator
( condition) ? value1 : value2
The ternary operator is described in the Miscel­laneous section of the Operators block as well. It is basically a very condensed if..then statement.
Nil-Coalescing oprerator
( a ?? b )
Unwraps a and returns it, if it is NOT nil. If it is nil, then b is returned.

Flow Control ( Looping )
for value in array { 
This loop, iterates over each of the elements within an array (or dictio­nary) and the variable value takes the value of an element, one at a time.
for loop
for initCond; chkCond; operator { 
The for loop basically a counts from an initial condition (iniCond) to an end condition (!chkCond) using an operator to change the value of the counter.
while loop
while condition { 
This code block is executed whenever the condition is true. The condition thus gets evaluated at the beginning.
do..while loop
do {
} while condition
This is a special case of the while loop, as the evaluation is at the end, instead of the beginning. The code block is executed at least once.

Flow Control ( Statements )

As seen before, the fall through statement is used within the switch block. It allows tho execute the next case of the matching section.
Continue allows to skip the rest of a iteration and
This statement allows to break out of a loop. It skips the rest of a iteration and aborts all subsequent loops.


func fName(parameter:Type)->Type {
 return Value
The function has to return a value of the same type that has been declaren in it's header. If we don't declare a return value, none has to be returned. Parameters are optional as well. A function without return value nor parame­ters, could look like this:
func fName() {
The function parameters may have a label. This would look like this (only declar­ation):
func fName(label parameter:Type)->Type {
Per defini­tion, all function parameters are passed as constants, so they are immutable. If we had to make changes to those parameters inside our function, and have this changes reflected outside as well, we'd use in/out parame­ters.
func fName(label parameter:inout Type)->Type {
Variadic parameters allow us to use an undefined amount of parameters (of the same type) inside our function.
func fName(parameter:Type...)->Type {
And lastly, if we wanted a default value to be assumed for a given parameter, we'd use:
func fName(label parameter:Type=value)->Type {
Consult: Docs for further inform­ation.


{( Parameters ) -> Type in //code }
Same as a function but without a name. Can be passed around in functions itself or variables.
let sum= {( n1:Int, n2:Int)->Int in
 return n1+n2
This would return the sum of two numbers when called like this:
let myResult = sum(2,3)
If the type of variables can be inferred, this is true for the sort(by:) function, the closure doesn't have to explicitly declare all types of variables. So instead of writing...
let myElements = ["two","three","four"]
let mySort­edE­lements =
myElements.sorted(by: {( prm1: String, prm2: String )->Bool in return prm1.c­har­act­ers.count > prm2.c­har­act­­unt})
...we could write (only closure part)...
let mySort­edE­lements = 
myElements.sorted(by: { prm1, prm2 in return prm1.c­har­act­ers.count > prm2.c­har­act­­unt})
This would return "­thr­ee",­"­fou­r","t­wo". But it doesn't stop here. To write it even shorter, we can skip the return keyword as well.
let mySort­edE­lements = 
myElements.sorted(by: { prm1, prm2 in prm1.c­har­act­ers.count > prm2.c­har­act­­unt})
Instead of declaring variables, names we can also use shorthands for the parame­ters. This could look like...
var myTest: (Int, Int)->Int
myTest = { $0 + $1 }
myTest(1,2) //This would return 3
Swift is even able o infer most of the closure and reduce it to the minimum.
let mySort­edE­lements = 
myElements.sorted(by: > )
Occasi­onaly, if a closure results to be very long, it can be written at the end of a header, after the parameter closing parent­hesis.
let mySort­edE­lements = 
myElements.sorted() {
  $0.cha­rac­ter­s.count < $1.cha­rac­ter­s.count
Consult Docs for further inform­ation.


enum Name {
 case Label1 [= Value]
 case Label2 (Type)
Enumer­atios are a way of labelling certain values to be used in the code.
enum Weekdays {
 case Mon, Tue, Wed, Thu, Fri, Sat, Sun
The way of referring to it is...
var myWeekDay = Weekda­ys.Mon
Consult Docs for further inform­ation.


struct PointS­truct { 
  var X:Int,
  var Y:Int
Structs may be used to encaps­ulate data. They can even have a initia­lizer to provide the struct with data.
struct PointS­truct { 
  var X:Int,
  var Y:Int
  init( x: Int, y: Int) {
    self.X = x
    self.Y = y
To declare a variable with this struct we would write...
let myPoint = PointS­truct( x: 1, y: 2 )
Structures are similar to classes with a few important differ­ences, being the most important one that their instances are always passed by value.
Consult Docs for further inform­ation.


class MyClass : MyProtocol { 
  var X:Int,
  init() {
  func myMethod() {
  deinit() {
Can be enumer­ations, variables or constants.
Declaration can be preceded by: lazy, static, private or public.
The methods init() and deinit() are special methods which are called upon instan­tiation and destru­ction of the class.
The method declar­ation can be preceded by one of the options: private, public, mutating, class or static
Protocols do specify a certain blueprint a class conforms to. See below


protocol MyProtocol {
  var myVariable : Type { get set }
  func myMethod ( parameter: Type)->Type
A protocol defines a blueprint of methods, properties and other requir­ements that suit a particular task or piece of functi­ona­lity. The protocol can then be adopted by a class, struct, or enum to provide an actual implem­ent­ation of those requir­ements. Any type that satisfies the requir­ements of a protocol is said to conform to that protocol.
Consult: Docs for further inform­ation.