Details for a topic

Control Flow

Learn basic Swift syntax for Control Flow : loops, tests.

This deck is used as a learning tool in the "iOS programming in Swift course" from the 3W Academy.

All cards

Control Flow

Do a simple test

if condition {
// do something
} else {
// do something else
}

Functions

Basic function without parameters

func doSomething() {
// some code
}

Functions

Function with arguments

func doSomething (x: Int, y: Int){
// do it
}

Functions

Function with String input and String output

func sayHi (name: String) -> String {
return "Hi \(name)"
}

Loops

Basic integer iteration

for index in 0...10 {
// do it from 0 to 10 included
}

Loops

Iterate over elements of an array

var myArray = ["toto", "titi"]
for firstName in myArray {
//do something with firstName
}

Loops

Iterate over elements of a dictionary

var myDict = ["John" : 14, "Paul" : 18]
for (name, age) in myDict {
print("\(name) is \(age)")
}

Loops

Iterate over an array with index

for (index, value) in myArray.enumerated() {
}

Switch

Simple switch

var myNumber = 2
switch myNumber {
case 1:
// do for 1
case 2:
// do for 2
default:
}

A break statement is not required


While loop

Simple while loop

while condition {
// do something
}

The code inside may never be executed. Beware of endless loops!


Loops

Simple repeat loop

repeat {
// do something
} while condition

Something is done at least once


Switch with interval matching.

This is specific to Swift.

switch myNumber {
case 0..<8:
//
case 8..<10:
//
default:
}

break

break terminates the execution of the control flow.

Can be used in a switch, or any loop statement : for, repeat, while


Functions

Function with multiple output

func sinCos (x : Double) -> (sin: Double, cos: Double) {
return (sin(x), cos(x))
}
// the output is a tuple and is accessed like this:
let cosx = sinCos(M_PI).cos
// returns -1