Defining Functions in Swift

Updated: February 22, 2023 By: Khue Post a comment

This concise, example-based article shows you how to define functions in Swift.

Defining a Basic Function

A basic function definition consists of the func keyword, a function name, a set of parentheses, and a set of curly braces that contain the function’s code.

Example:

func sayHello() {
    print("Hello friend! Welcome to slingacademy.com")
}

// call the function
sayHello()

Output:

Hello friend! Welcome to slingacademy.com

Our sayHello function doesn’t take any arguments or return any values. It simply prints a message to the console.

Defining a Function with Parameters

You can also define a function that takes one or more parameters. To do so, you simply list the parameter names inside the parentheses, separated by commas.

Example:

func greet(name: String) {
    print("Hello, \(name)!")
}

// call the function
greet(name: "Wolf")

Output:

Hello, Wolf!

The greet function takes one parameter called name of the type String. It uses string interpolation to print a personalized greeting to the console (do you know someone whose name is Wolf?).

Defining a Function that Returns a Value

In addition to taking parameters, a function can also return a value. To do so, you specify the return type of the function using an arrow -> followed by the type.

Example:

func square(number: Int) -> Int {
    return number * number
}

// call the function
let result = square(number: 5)
print(result)

Output:

25

Our square function can take one parameter named number of type Int. It returns the square of the input number as an Int.

Define a Function that Returns Multiple Values

In Swift, you can return multiple values from a function by using tuples. A tuple is a way to group multiple values into a single compound value.

Example:

func findMinMax(numbers: [Int]) -> (min: Int, max: Int) {
    var min = numbers[0]
    var max = numbers[0]
    for number in numbers {
        if number < min {
            min = number
        }
        if number > max {
            max = number
        }
    }
    return (min, max)
}

// use the function
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let minMax = findMinMax(numbers: numbers)
print("min: \(minMax.min), max: \(minMax.max)")

Output:

min: 1, max: 10

Function Parameter Labels and Argument Labels

Swift functions allow for two different names for each function argument: the parameter label and the argument label. The parameter label is used inside the function, while the argument label is used when calling the function.

Example:

func greet(person name: String) {
    print("Hello, \(name)!")
}

greet(person: "Sling Academy")

Output:

Hello, Sling Academy!

When calling the function greet, we use the argument label person to specify which argument we’re passing in.

Define a Function with Optional and Default Parameters

In Swift, you can define a function with optional and default parameters. Optional parameters allow you to omit certain arguments when calling the function, while default parameters provide a default value for a parameter if no value is provided.

Example

This examples define a function named greet that can take up to 3 parameters: name of type String (required), greeting of type String with a default value of Hello, and times of type Int? (optional).

func greet(name: String, greeting: String = "Hello", times: Int? = nil) {
    if let times = times {
        for _ in 1...times {
            print("\(greeting), \(name)!")
        }
    } else {
        print("\(greeting), \(name)!")
    }
}

// call the function 
greet(name: "Alice") 
greet(name: "Bob", greeting: "Hi")
greet(name: "Charlie", times: 3) 

Output:

Hello, Alice!
Hi, Bob!
Hello, Charlie!
Hello, Charlie!
Hello, Charlie!