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
func sayHello() {
print("Hello from Workownix")
}
func add(a: Int, b: Int) -> Int {
return a + b
}
sayHello()
print(add(a: 7, b: 5))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
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))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
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)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
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)")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
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)[10, 4, 18, 8, 14] [5, 9, 7] [2, 4, 5, 7, 9] 27
| Method | What it does |
|---|---|
map | Changes each item and returns a new array |
filter | Keeps items where the closure returns true |
sorted | Returns the items in order |
reduce | Combines 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)?
