SwSwift
BeginnerLesson 4 of 16

Functions & Argument Labels – Swift

Parameters, default values, return values, inout, and functions as values.

You define functions with func. Every parameter has an argument label (for the caller) and a parameter name (inside the function body). With _ you omit the label. If the function consists of a single expression, you can leave out return.

func begruesse(_ name: String, gruss: String = "Hello") -> String {
    "\(gruss), \(name)!"
}

print(begruesse("Ada"))                  // Hello, Ada!
print(begruesse("Linus", gruss: "Hi")) // Hi, Linus!

func summe(_ zahlen: Int...) -> Int {    // variadic
    zahlen.reduce(0, +)
}
print(summe(1, 2, 3, 4))                 // 10

A (named) tuple returns multiple values; an optional indicates “no result”. With inout (called with &), a function modifies the variable passed in.

func minMax(_ zahlen: [Int]) -> (min: Int, max: Int)? {
    guard let erstes = zahlen.first else { return nil }
    var lo = erstes, hi = erstes
    for x in zahlen {
        if x < lo { lo = x }
        if x > hi { hi = x }
    }
    return (lo, hi)
}

if let ergebnis = minMax([3, 9, 1, 7]) {
    print(ergebnis.min, ergebnis.max)    // 1 9
}
print(minMax([]) == nil)                 // true

func verdopple(_ x: inout Int) { x *= 2 }
var zahl = 4
verdopple(&zahl)
print(zahl)                              // 8

Functions are first-class values: you can store them in variables, pass them as parameters, and return them. Local functions can even capture variables of the enclosing function.

func rechne(_ a: Int, _ b: Int, mit operation: (Int, Int) -> Int) -> Int {
    operation(a, b)
}
func addiere(_ a: Int, _ b: Int) -> Int { a + b }

print(rechne(3, 4, mit: addiere))        // 7
print(rechne(3, 4, mit: *))              // 12  (an operator is also a function)

func potenzierer(hoch n: Int) -> (Int) -> Int {
    func potenz(_ x: Int) -> Int {
        var ergebnis = 1
        for _ in 0..<n { ergebnis *= x }
        return ergebnis
    }
    return potenz
}
print(potenzierer(hoch: 3)(2))           // 8
TipGood argument labels read like a sentence: zahlen.firstIndex(of: 3), liste.insert(x, at: 0). These are the Swift API Design Guidelines; follow them in your own functions.
WarningParameters inside functions are constants. func f(x: Int) { x += 1 } does not compile. If you want to change the caller's value, you need inout; if you only calculate locally, create a var copy.