Swift Tutorial menu

Swift Functions and Closures

A function is a reusable block of code with a name. You call it whenever you need that job done.

Defining a Function

Use func, a name, and a pair of brackets. Return types come after ->.

Example

swift
func sayHello() {
    print("Hello from Workownix")
}

func add(a: Int, b: Int) -> Int {
    return a + b
}

sayHello()
print(add(a: 7, b: 5))
Output
Hello from Workownix
12

When you call a function, Swift asks you to write the parameter names, like add(a: 7, b: 5). This makes calls easy to read.

Argument Labels

A parameter can have an argument label (used when calling) and a parameter name (used inside the function). Use _ when you want no label.

Example

swift
func send(message text: String, to person: String) {
    print("To \(person): \(text)")
}

func square(_ n: Int) -> Int {
    n * n
}

send(message: "Class starts at 4 pm", to: "Ayesha")
print(square(9))
Output
To Ayesha: Class starts at 4 pm
81

When a function has a single expression, you can leave out return, as in square.

Default Values

Example

swift
func orderPizza(size: String = "Medium", extraCheese: Bool = false) {
    let cheese = extraCheese ? "with" : "without"
    print("\(size) pizza \(cheese) extra cheese")
}

orderPizza()
orderPizza(size: "Large")
orderPizza(size: "Small", extraCheese: true)
Output
Medium pizza without extra cheese
Large pizza without extra cheese
Small pizza with extra cheese

Returning Several Values

A function can return a tuple, a small group of values:

Example

swift
func minMax(_ numbers: [Int]) -> (min: Int, max: Int) {
    var low = numbers[0]
    var high = numbers[0]
    for n in numbers {
        if n < low { low = n }
        if n > high { high = n }
    }
    return (low, high)
}

let result = minMax([45, 12, 88, 30])
print("Lowest: \(result.min), highest: \(result.max)")
Output
Lowest: 12, highest: 88

Closures

A closure is a function without a name that you can pass around. You write it inside curly braces. Inside short closures, $0 is the first argument.

Example

swift
let numbers = [5, 2, 9, 4, 7]

let doubled = numbers.map { $0 * 2 }
let big = numbers.filter { $0 > 4 }
let ordered = numbers.sorted()
let total = numbers.reduce(0, +)

print(doubled)
print(big)
print(ordered)
print(total)
Output
[10, 4, 18, 8, 14]
[5, 9, 7]
[2, 4, 5, 7, 9]
27
MethodWhat it does
mapChanges each item and returns a new array
filterKeeps items where the closure returns true
sortedReturns the items in order
reduceCombines all items into one value

The full form of a closure names its parameters: numbers.map { (n: Int) -> Int in return n * 2 }. The short form with $0 does the same thing.

In SwiftUI apps, closures are everywhere: a button's action is a closure that runs when the user taps it.

Exercise

Exercise

How do you call func greet(_ name: String)?

Learn Swift with a teacher

Join the App Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp