TExcelTAD
Home › Swift › Swift Functions

Swift Functions

A function is a named block of code that performs one task. You define it once and call it as often as you like. Functions make programs shorter, easier to read and easier to test.

Defining and calling a function

Use the func keyword, a name, a parameter list in parentheses and a body in braces:

swift · try it yourself
func sayHello() {
    print("Hello from a function!")
}

sayHello()
sayHello()
Hello from a function!
Hello from a function!

Parameters and return values

Each parameter has a name and a type. The return type follows an arrow ->:

swift · try it yourself
func square(number: Int) -> Int {
    return number * number
}

func describe(name: String, age: Int) -> String {
    "\(name) is \(age) years old"   // single expression: return is implicit
}

print(square(number: 9))
print(describe(name: "Kofi", age: 28))
81
Kofi is 28 years old

Note: When a function body is a single expression, you can leave out return.

Argument labels

Swift functions read like sentences because each parameter can have an argument label (used by the caller) that differs from the parameter name (used inside the function). Write _ as the label to omit it at the call site:

swift · try it yourself
// label "to", parameter name "recipient"
func send(_ message: String, to recipient: String) {
    print("Sending '\(message)' to \(recipient)")
}

func move(from start: Int, to end: Int) -> Int {
    end - start
}

send("Lunch at 12?", to: "Priya")
print("Distance:", move(from: 3, to: 10))
Sending 'Lunch at 12?' to Priya
Distance: 7
Declaration Call
func f(x: Int) f(x: 1)
func f(_ x: Int) f(1)
func f(at x: Int) f(at: 1)

Default values and variadic parameters

A parameter can have a default value, which makes it optional for the caller. A variadic parameter (Type...) accepts any number of values and arrives as an array:

swift · try it yourself
func makeCoffee(size: String = "medium", sugar: Int = 0) -> String {
    "A \(size) coffee with \(sugar) sugar"
}

func average(_ values: Double...) -> Double {
    guard !values.isEmpty else { return 0 }
    var sum = 0.0
    for v in values { sum += v }
    return sum / Double(values.count)
}

print(makeCoffee())
print(makeCoffee(size: "large"))
print(makeCoffee(sugar: 2))
print(average(4, 8, 6))
print(average())
A medium coffee with 0 sugar
A large coffee with 0 sugar
A medium coffee with 2 sugar
6.0
0.0

Returning multiple values

Return a tuple when a function produces more than one result, and an optional when the result might not exist:

swift · try it yourself
func divide(_ a: Int, by b: Int) -> (quotient: Int, remainder: Int)? {
    if b == 0 { return nil }
    return (a / b, a % b)
}

if let result = divide(17, by: 5) {
    print("17 / 5 = \(result.quotient) remainder \(result.remainder)")
}

if divide(1, by: 0) == nil {
    print("Can't divide by zero")
}
17 / 5 = 3 remainder 2
Can't divide by zero

inout parameters

Parameters are constants inside the function. To let a function change a variable from the caller, mark the parameter inout and pass the variable with &:

swift · try it yourself
func double(_ value: inout Int) {
    value *= 2
}

var points = 21
double(&points)
print(points)

func swapValues(_ a: inout String, _ b: inout String) {
    let temp = a
    a = b
    b = temp
}

var first = "tea", second = "coffee"
swapValues(&first, &second)
print(first, second)
42
coffee tea

Function types and overloading

Functions are values too: they have a type such as (Int, Int) -> Int and can be stored in variables or passed to other functions. Swift also allows several functions with the same name if their parameters differ (overloading):

swift · try it yourself
func add(_ a: Int, _ b: Int) -> Int { a + b }
func multiply(_ a: Int, _ b: Int) -> Int { a * b }

var operation: (Int, Int) -> Int = add
print(operation(6, 7))
operation = multiply
print(operation(6, 7))

func describe(_ value: Int) -> String { "an integer: \(value)" }
func describe(_ value: String) -> String { "a string: \(value)" }
print(describe(5))
print(describe("five"))
13
42
an integer: 5
a string: five

Passing functions around leads directly to closures, the topic of the next chapter.

Tip: Name functions after what they do, using verbs (calculateTotal, send(_:to:)), and choose argument labels so the call reads naturally in English.

Test yourself

Given func greet(_ name: String), how do you call it?

  1. greet(name: "Ana")
  2. greet("Ana")
  3. greet(_: "Ana")
  4. greet["Ana"]

What keyword lets a function modify a variable passed by the caller?

  1. var
  2. mutating
  3. inout
  4. ref

What is the type of func add(_ a: Int, _ b: Int) -> Int?

  1. Int
  2. (Int, Int) -> Int
  3. func(Int, Int)
  4. (a: Int, b: Int)