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.
Do a simple test
if condition {
// do something
} else {
// do something else
}Basic function without parameters
func doSomething() {
// some code
}Function with arguments
func doSomething (x: Int, y: Int){
// do it
}Function with String input and String output
func sayHi (name: String) -> String {
return "Hi \(name)"
}Basic integer iteration
for index in 0...10 {
// do it from 0 to 10 included
}Iterate over elements of an array
var myArray = ["toto", "titi"]
for firstName in myArray {
//do something with firstName
}Iterate over elements of a dictionary
var myDict = ["John" : 14, "Paul" : 18]
for (name, age) in myDict {
print("\(name) is \(age)")
}Iterate over an array with index
for (index, value) in myArray.enumerated() {
}Simple switch
var myNumber = 2
switch myNumber {
case 1:
// do for 1
case 2:
// do for 2
default:
}A break statement is not required
Simple while loop
while condition {
// do something
}The code inside may never be executed. Beware of endless loops!
Simple repeat loop
repeat {
// do something
} while conditionSomething 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
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