Functions

Swift functions have one quirk that trips up newcomers from almost every other language: every parameter can have both an external argument label (what the caller writes) and an internal parameter name (what the function body uses), and by default they're different.

A basic function

Swift main.swift
func add(a: Int, b: Int) -> Int {
    return a + b
}

print(add(a: 3, b: 4))
Output
7

Calling add requires writing the parameter names at the call site — add(a: 3, b: 4), not add(3, 4). That's the default behavior: parameter names double as required argument labels unless you say otherwise.

Argument labels vs parameter names

Swift main.swift
func greet(to name: String) {
    print("Hello, \(name)!")
}

greet(to: "Priya")
Output
Hello, Priya!

to name: String means callers write to: as the label, but inside the function body the parameter is just name. This reads naturally at the call site (greet(to: "Priya")) while keeping a shorter, more natural name inside the function.

Omitting the label with underscore

Swift main.swift
func square(_ n: Int) -> Int {
    return n * n
}

print(square(6))
Output
36

Default parameter values

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

greet(name: "Sam")
greet(name: "Sam", greeting: "Hey")
Output
Hello, Sam!
Hey, Sam!
Note: the _ before a parameter name (as in square(_ n: Int)) explicitly drops the argument label for that parameter, so callers can write square(6) instead of square(n: 6). It's common on the first parameter of a function whose name already makes the argument's purpose obvious.