CodeToLive

Functions & Closures in Swift

Functions are self-contained chunks of code that perform specific tasks.

Basic Function

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

Parameter Labels

func move(from start: String, to end: String) {
    print("Moving from \(start) to \(end)")
}
move(from: "Home", to: "Work")

Default Parameters

func count(to end: Int, start: Int = 1) {
    for i in start...end {
        print(i)
    }
}
count(to: 5)  // Uses default start=1

Closures

let names = ["Chris", "Alex", "Ewa"]
let sortedNames = names.sorted(by: { $0 > $1 })
print(sortedNames)

Trailing Closures

let numbers = [16, 58, 510]
let digitNames = numbers.map { number in
    String(repeating: "★", count: number)
}

Function Types

func add(a: Int, b: Int) -> Int { a + b }
var mathFunction: (Int, Int) -> Int = add
print(mathFunction(2, 3))  // 5
← Back to Tutorials