# Swift Introduction/Printable version

The current, editable version of this book is available in Wikibooks, the open-content textbooks collection, at
https://en.wikibooks.org/wiki/Swift_Introduction

# Introduction
## What is Swift?

Swift is an open source programming language, introduced by Apple in 2014. It is used for their operating systems macOS for desktops and iOS for mobile devices, for instance iPhone or iPad. Since 2015 Swift has also been available on Linux under the Apache Licence 2.0. It is a modern language that includes multiple paradigms like object orientation, functional- and imperative programming. Apple included useful features from other languages like C#, Ruby, Python or Haskell.

## Swift on Linux
### Install

Before you can start with Swift, you first have to download and install the compiler and other components. Those can be downloaded from Swift's download page. On Linux, clang has to be installed too using following command:

### IDE for Linux

Xcode is only available on macOS. However, there are alternatives which provide similar functionality:
* JetBrain's CLion offeres a Swift extension which features code highlighting and completion and also a debugger.
* The Open-Source Editor Atom offeres a plugin that works similar to Xcode's playground where you can easily try new code and immediatly see what it does.

## First example

Before we dive right into Swift's basic and advanced features, let's have a look at the world-famous "Hello World" example.
Now, let's have a first glance at what variables and constants look like.

## References

* ↑ Apache Software Foundation [online][accessed: 18.09.2017] | https://www.apache.org/licenses/LICENSE-2.0
* ↑ Swift.org [online][accessed: 18.09.2017] | https://swift.org/getting-started/
* ↑ clang [online][accessed: 18.09.2017] | https://clang.llvm.org
* ↑ JetBrain Swift Plugin [online][accessed: 18.09.2017] | https://blog.jetbrains.com/clion/2015/12/swift-plugin-for-clion/
* ↑ Atom.io Swift Playground [online][accessed: 18.09.2017] | https://atom.io/packages/swift-playground

# Swift Basics

In this chapter, you will learn how to use the basic concepts of Swift, including variables, constants and arrays. Another important topic covered in this chapter is how functions and classes are written in Swift.

## Variables and Constants

Like in most other languages, Swift uses variables to store values and to refer to them by an unique name. The values of these variables can be mutable or immutable. It's good practice to use constants whenever the value of it does not have to be changed in the code later. This also makes the code you writer safer.

### Declaring a variable

In Swift, variables are declared with the keyword var. It is recommended to use var only if you need to change the value of the variable later.

### Declaring a constant

If it is not necessary to change a variable's value it can be declared with the keyword let.

### Type Annotations

Type annotations can be used to be clear about what kind of values a constant or a variable can store. This is necessary if there is no initial value. If an initial value is provided, Swift infers which type the variable should have.

### Changing Values

If a variables value should be changed, it has to be of the same type of the original value. In this example, the value of greeting is changed to another String "Good evening".

## Datatypes
### Type Safety and Type Inference

Swift is a type-safe language, which means for example it is not possible to assign a number to a variable that stores a String or to call a function with parameters of the wrong type. At compile-time Swift performs type checks and finishes without error only when there are no mismatched types.
If you declare a variable or a constant without specifying the type Swift uses Type Inference to find out the appropriate type. If you provide a floating-point number when declaring a variable, Swift inferes it to be a value of the type Double.

### Integer

Integers are whole numbers like 45 or -37. They do not have a fractional component and are signed or unsigned. If an Integer is signed it can be zero, a positive or a negative number. Unsigned Integers can only be zero or positive. Swift provides Integer Types in 8, 16, 32 and 64 bit form. Although it is possible to pick a specific size, for example UInt8 or Int32, in most cases the Int type is used. It has the same size as the platform's native word size. In modern Operating Systems it has a size of 64 Bit. Uint is an unsigned Integer Type which also has the size of the platform's word size.

### Floating Point Numbers

Floating-point numbers which have a fractional component can represent values which are much larger or much smaller than the possible values of an Int. Numbers like -0.0001 or 19.99 can be stored in variables of the type Double or Float. Double, a 64 Bit floating-point number, has a precision of at least 15 decimal digits. Float provides a precision of 6 decimal digits.

### Booleans

In Swift, the Boolean datatype is called Bool and can have the constant values true or false.
Boolean values work great with control flow operations like if statements:

### Optionals

Optional variables have two possible states: There is a value or there is no value. For declaring a variable with an optional datatype a ? is used.
To find out whether a value has already been set or not you can use an if statement and the == (equal to) or != (not equal to) operators.
In the example above you can see an exclamation mark at the end of the optionals name. It is used to unwrap the value of the optional to use it. If a ! is used on an optional which contains no value a runtime error will be triggered.

### Optional Binding

Optional binding checks whether an optional is set, and if so, its value is set to a new variable or constant which is temporarily available.
The new constant netSalary is only available within the if-Statement and does not have to be unwrapped.

## Collection Types

In Swift there are three primary collection types.
* Array for an ordered collection of values
* Set for an unordered collection of unique values
* Dictionary for unordered key - value pairs
Just like variables and constants, all three collection types are type safe, which means it is not possible to insert a value of the wrong type. The positive aspect of this type safety is, that you always know which type the value you get from a collection has.
Arrays, sets and dictionaries that are assigned to a variable are mutable, which means values can be added, changed or deleted after they were created. If you need a immutable collection type it has to be assigned to a constant.

### Array

Arrays provide an ordered list of elements of the same type. There are two ways to declare an array, Array<Element> or [Element]. Element is the type of the values that should be stored in the array. Arrays can be created empty or filled with values. It's also possible to create the Array with a default value.
Arrays can also be initialized with array literals. This is a list of values, separated by commas.

#### Properties and Methods of Arrays

Subscript syntax is used to access the elements in an array. The index starts at zero, which means for accessing the first element of your array you have to add [0] to the array's name.

### Set

A set stores values of the same type and is used when the order of the items is not important. Sets also ensure, that no duplicate values appear. Values can only be stored in a set, if they are hashable. Swift's basic types like String, Int and Bool are all hashable by default.
Sets offer a huge amount of set operations. These operations implement the most important rules of the mathematical set theory.
* intersection
* symmetricDifference
* union
* subtracting
The following snippet shows how these operations work.

### Dictionary

Dictionaries store Key - Value pairs in an unordered collection. The key is an unique identifier for the value. Similar to arrays, there are two ways to declare a dictionary. Dictionary<Key, Value> or [Key: Value]. Moreover dictionaries can also be created using dictionary literals.

## Control Flow

Swift provides a lot of ways to control the way your code is executed.

### For-In Loop

Using a For-In Loop is an easy way to iterate over an array, a set or any other type of sequence or range.
In a typical For-In Loop the counter always increases by 1. If you want to make smaller or bigger steps, you have to use stride.

### While Loop

While Loops are very useful if you do not know how many iterations you need. A while loop executes statements as long as a condition is true. There are two types of while loops.
* while checks whether the condition is true before the statements are executed.
* repeat-while executes the statements and checks if the condition is still true at the end.

### If

The if statement is the simplest way to decide which statements should be executed, based on certain conditions. It is used if there are just a few possible conditions. The if statemant can stand alone, but it's best practice to always provide an else statement as well, because it makes the code more readable and understandable. === Switch ===
It is also possible to provide different code paths for more than just one condition:
As you can see, a growing number of conditions leads to a lot of duplicated code. A switch statement can be used to reduce the amount of duplicated code.

### Switch

A switch statement usually has several possible cases for the condition it checks. All switch statements have to be exhaustive, which means every possibe value of the condition has to have a case. Therefor a default statement should be provided which is executed if none of these cases fit.

## Functions

Functions are an important part of your code. They have an identifying name - it's best practice to use a name which describes what the function does - which is used when you call the function. They can have zero to many parameters. Those input values are passed in as soon as you call the function.

### Defining and Calling Functions

In the code snippet below, you can see the definition of a function begins with fund followed by the name and an optional parameter list. The -> operator specifies the return type of this function. A function which does not have the arrow in the definition does not have a return value.

### Parameters and Return Values

Functions can have zero to many parameters and also zero to many return values. In the example below, you can see a function which takes two integer values as arguments and returns two integer values. The second function has no arguments and no return value.

### Argument Labels and Parameter Names

In Swift, parameters have an argument label which is used when calling the function and a parameter name, which is used in the implementation.
It is also possible to write functions without argument labels.

### Variadic Parameters

These parameters accept a variable number of arguments of the same type. It is especially useful when you do not know the exact number of arguments you want to pass to the function or the number of required arguments changes from one function call to the next.

### Function Types

A function's type consists of the parameters types and its return type. Let's take a look at the function type of one of the functions from the snippets above.
This function is made up from two arguments of type Double and a return type String. Therefor the function type is (Double, Double) -> String
Functions can also have function types as return values.

### Nested Functions

Functions which are defined inside another function are called nested functions. They are not visible outside the function. However, they can be used outside the function if the enclosing function returns it.

## Classes and Structures

As an object-oriented language, Swift also provides classes, the construction plan for objects or instances, and structures, a similar construct. Interfaces, which are used to make the class or the structure available for other code parts, are available automatically.
Classes and structures share a lot of features, for example:
* Properties to store values
* Methods which provide functionality
* Both can be extended
* Initializers to set up their initial state
However, there are some features only classes provide:
* Inheritance
* Check and interpret a classes type at runtime
* Class can free up ressources using Deinitializers

### Class or Structure?

Before deciding whether a class or a structure suits better for your needs, a few characteristics of both constructs have to be considered. One of the most important differences is, that class are always passed by reference whereas structures are passed by value.
Apple suggests using structs in these situations:
* The primary purpose of the structure is to encapsulate few simple data values.
* It is reasonable to expect that the values will be copied and not referenced.
* All properties within the structure are value types.
* The structure does not need to inherit properties or behavior from other existing types.
In the snippet below you can see two structures, SoftTyre and HardTyre, which store values that describe the characteristics of a tyre. As you can see, only simple values like Integers and Bools are stored. The class Racecar also includes some simple data values like weight or teamName, but also an instance of the SlickTyre structure.

### Accessing Properties

Properties of classes and structures can be accessed using dot syntax.

### Memberwise initialization of Structure Types

The properties of a new structure instance can be initialized using memberwise initializers which are automatically generated.

### Value Type vs. Reference Type

Structures, Enumerations and all basic types in Swift, for example integers, strings and arrays, are value types, which means the value is copied when it is passed to a function. Changes to a copied value of an integer inside a function do not affect the original value outside.
Classes are reference types, which means they are not copied when they are passed to a function. Instead, references to already existing instances are used. In the snippet below, an instance of Racecar is assigned constant called rb13. After assigning the properties raceWins and weightEmpty rb13 is assigned to a new constant rb14. As the instance of the Racecar class is passed by reference, changes in rb14 automatically affect the properties in rb13.

## References

* ↑ Apple Inc. | 2017 | Swift programming language | [online][accessed: 18.09.2017] | https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/index.html#//apple_ref/doc/uid/TP40014097-CH3-ID0
* ↑ Apple Inc. | 2017 | Swift - Classes and Structs | [online][accessed: 18.09.2017] | https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ClassesAndStructures.html#//apple_ref/doc/uid/TP40014097-CH13-ID82

# Swift Advanced
## Closure Expressions

Closure expressions are unnamed, anonymous functions which can interact with values from their surrounding contextref name="error">Apple Inc. | 2017 | Closure Expressions | [online][accessed: 18.09.2017] | https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html#//apple_ref/doc/uid/TP40014097-CH11-ID94</ref>. They are short function-like constructs without a declaration or name. In this snippet, you can see the general syntax of a closure expression. It starts with opening curly brackets, a parameter list and a return value. They keyword in marks the beginning of the closure's body. After the return statement the expression is closed with a curly bracket.
If a closure is assigned to a function type, a shorthand syntax can be used because Swift can infer the data types from the context. In the shortest version, you only have to tell Swift what to do with the parameters. $0 is short syntax for the first passed in argument, $1 for the second, and so on.

### Trailing Closures

Closures can be passed to functions as arguments. A trailing closure can be used as the function's final argument. It's not written within the functions parentheses but right after them. In the snippet below, you can see how a closure is passed to Swift's map function. The map function can be called on an array, the closure is then executed on every item of the array. In this example, the map functions checks whether a year is a leapyear or not. All years are converted to a string and " is a leap year" is appended if the prerequisites are fulfilled.

## Properties

In Swift, there are two main types of properties. Stored properties are used to store values of variables and constants associated with a class or a structure. Computed properties are not used to store, but to compute values.

### Stored Properties

These properties are a part of an instance of a class or a structure. It can have a variable or a constant value.

### Computed Properties

These properties provide getters and setters to retrieve or set the value of a variable. In this example, the structure Circle has a computed property called diameter. It has a getter which returns the doubled value of the radius. The setter changes the value of the radius to the half of the new diameter. area is a read-only property, which means it does not have a setter.

### Property Observers

Property observers can be used to observe the state of a property and respond to changes. They are called whenever the value of a property is set. There are two types of observers. willSet is called before a value is stored, didSet is called after a value is stored.

## Concurrency with GCD

The dispatch framework includes a lot of language features, runtime libraries and system enhancements which improve the support for concurrent code execution on hardware with more than one core. The Grand Central Dispatch (GCD) submittes work to dispatch queues managed by the system.

### Concurrency vs. Parallelism

Parallelism is the term which describes the concept of executing two or more threads at the same time on multi-core processors. Devices with a single core can achieve concurrency with time-slicing. This is the process of switching between multiple threads through context switches. GCD manages a pool of threads. Codeblocks can be added to dispatch queue and the GCD decides what to execute.

### Queues

DispatchQueue represents the dispatch queues provided by GCD. The tasks, which you submit to the queues, are executed in a FIFO order, which means the first submitted task will always be the first one that gets started. There are two types of queues. Serial queues can only execute one task at any time. Concurrent queues can start multiple tasks at the same time. They are started in the order they were added and can finish in any order. The scheduling is managed by GCD, which means it controls when tasks are started. GCD provides a main queue, which is a serial queue and runs on the main thread. Tasks on the main queue are executed immediately. It is good practice to put all tasks, which change or update the UI, on the main queue. This makes sure the UI is always responsive. The four global queues are concurrent, shared by the entire system and divided in priorities - high, default, low and background. Queues can also be created by the user and can be serial or concurrent.
The priority is not specified directly, but by using Quality of Service (QoS) classes.
.user-interactive describes tasks which have to be done immediately, because otherwise the user experience would be bad. This QoS is used for UI updates and event handling.
.user-initiated represents tasks, which can be performed asynchronously and are started from the UI. These tasks are mapped into the high priority queue, because it is used when users are waiting for immediate results or tasks require user interaction to continue.
.utility represents long-running tasks. This class is used for I/O, networking and computations. Usually a progress indicator is used to make sure the user knows something is going on.
.background describes tasks, which the user usually is not aware of. It is used for tasks that do not need user interaction and are not time-sensitive, for example maintenance or prefetchting.

### Using queues in iOS

The following snipped can be found on Github and can be imported as Xcode project. As soon as the "Start" button is pressed, the function download(size: Int, label: UILabel, timeout: Int) is called twice with different input parameters. After they are put onto a global queue they asynchronously execute the simulation. After each iteration the amount is increased by 1. Next, the label which displays the progress of the download has to be updated. To do this, it is necessary to put the task back on the main queue, which makes sure that it is executed immediately. After a short timeout the next iteration starts.

## Error Handling

There are a lot of situations where errors can occure during the execution of your code. For example, when trying to read a file from your harddisk errors can occur due to missing permission or non-existing files. Swift provides couple of ways to deal with errors during code execution.
* Errors in a function can be propagated to the code calling the function
* do-catch statements
* optional values
* assert the error won't occur

### Propagating Errors with throwing Functions

The keyword throws is used in a function's declaration after the parameterlist. This function is then called a "throwing function". In the example below, an enum is used to define two types of possible errors. Whenever the makeCoffee function is called, the number of beans in the machine is decreased and a counter is increased. As soon as the beans are empty, an outOfBeans error is thrown. If a certain number of cups was served, the needsMaintenance error is thrown.

### Do-Catch

Do-Catch statements are used to execute different statements depending on what type of error is thrown. For example, here a needsMaintenance error is caught, the machine asks for maintenance and the counter is set back to 0.

### Converting Errors to Optional Values

With the try? keyword, an error is converted to an optional value. The value of an expression is nil whenever an error is thrown during the execution. In the snippet below, an error is thrown as soon as the digit that should be returned is no longer greater than zero.

## Accessing data from Sensors

Apple's mobile devices include a lot of sensors, including an Accelerometer, a Barometer, an Ambient light sensor and a Pedometer. iOS developers can access these sensors data in their projects with Swift.

### Pedometer

As an example, the snippet below shows how the Pedometer can be accessed and how data can be retrieved. This sensor is used for instance to count a persons steps. This project can be downloaded from GitHub.

## Unit Testing

In this section we will have a look at how simple unit tests can be implemented in Swift. For this purpose a simple class with three functions will be tested. The class contains variables for two integer values and three functions which can add, subtract or multiply those values.
Next, let's have a look at how this class can be tested. First of all we have to import the XCTest testing framework and the Calculator. In the test functions testAdd, testSub and testMul an instance of the Calculator class is used to call the methods add, subtract and multiply to compare the result to an expected value.

## References

* ↑ Kodeco | 2017 | Grand Central Dispatch Tutorial | [online][accessed: 18.09.2017] | https://www.kodeco.com/5370-grand-central-dispatch-tutorial-for-swift-4-part-1-2
* ↑ Apple Inc. | 2017 | Error Handling | [online][accessed: 18.09.2017] | https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html#//apple_ref/doc/uid/TP40014097-CH42-ID508
* ↑ Apple Inc. | 2017 | [online][accessed: 18.09.2017] | https://developer.apple.com/documentation/coremotion/cmpedometer
* ↑ Nolan, G. (2017), Agile Swift: Swift Programming Using Agile Tools and Tech- niques, Springer Science+Business Media New York, New York

# Conclusion
## Open Issues

This book includes many of the most important concepts of Swift. It explains the basics like datatypes, control flow and collection types. It also deals with advanced topics like concurrency and unit testing. Of course there are a lot of other language features which are not described here, for instance inheritance, generics and protocols.

## Consequences and Suggestions

To take advantage of all language features I recommend reading Apple's Language Guide which describes all basic features as well as a lot of advanced topics. Moreover, I can suggest video blogs or video courses from Stanford University . There you can find a lot of free tutorials for iOS development.

## References

* ↑ Apple Inc. | 2017 | Swift programming language | [online][accessed: 18.09.2017] | https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/index.html#//apple_ref/doc/uid/TP40014097-CH3-ID0