</>
Skip to content
Swift lessons (15/33)

Swift — Functions

Basic functions

func greet(name: String) -> String {
    return "Hello, \(name)!"
}

print(greet(name: "Alice"))

Multiple return values

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

if let result = minMax([3, 1, 4, 1, 5, 9]) {
    print("Min: \(result.min), Max: \(result.max)")
}

Default parameters

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

greet(name: "Alice")           // Hello, Alice!
greet(name: "Bob", greeting: "Hi") // Hi, Bob!

Variadic parameters

func sum(_ numbers: Int...) -> Int {
    numbers.reduce(0, +)
}

print(sum(1, 2, 3))       // 6
print(sum(1, 2, 3, 4, 5)) // 15

inout parameters

func swap(_ a: inout Int, _ b: inout Int) {
    let temp = a
    a = b
    b = temp
}

var x = 1, y = 2
swap(&x, &y)
print(x, y) // 2 1

Closures

// Basic closure
let add = { (a: Int, b: Int) -> Int in
    return a + b
}
print(add(3, 4)) // 7

// Trailing closure
let nums = [1, 2, 3, 4, 5]
let evens = nums.filter { $0 % 2 == 0 }
print(evens) // [2, 4]

// Shorthand
let doubled = nums.map { $0 * 2 }
print(doubled) // [2, 4, 6, 8, 10]

Higher-order functions

func applyTwice(_ f: (Int) -> Int, _ x: Int) -> Int {
    f(f(x))
}

let double = { $0 * 2 }
print(applyTwice(double, 3)) // 12

Mini Practice

Write Swift code that:

  1. Creates a function with default parameters
  2. Returns multiple values from a function
  3. Uses a closure with trailing closure syntax
  4. Chains filter, map, and reduce

Up Next

In the next lesson, you'll learn about Closures — functional programming in Swift.

Related Topics

Frequently Asked Questions about Functions

What is Functions in Swift?

Functions is a fundamental concept in Swift. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Functions?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Functions.

Why is Functions important in Swift?

Functions is essential for Swift development. Understanding this concept will help you write better code and solve real-world problems more effectively.