Swift Introduction/SwiftBasics

= 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. It is recommended to use  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.

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  "Good evening".

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  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.

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  or , in most cases the   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. 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. Numbers like -0.0001 or 19.99 can be stored in variables of the type or. , a 64 Bit floating-point number, has a precision of at least 15 decimal digits. provides a precision of 6 decimal digits.

Booleans
In Swift, the Boolean datatype is called  and can have the constant values or.

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  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,  or. 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. or. 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  and a return type. Therefor the function type is

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. After assigning the properties raceWins and weightEmpty  is assigned to a new constant rb14. As the instance of the Racecar class is passed by reference, changes in  automatically affect the properties in.