Parameters and Argument Labels
Prerequisites: Functions
Swift functions have unusually expressive parameters. Learning them makes Apple's frameworks much easier to read.
Argument labels vs parameter names
Each parameter can have two names: an argument label used when calling, and a parameter name used inside the function:
func send(_ message: String, to recipient: String) {
print("To \(recipient): \(message)")
}
send("Hi!", to: "Ada")
To Ada: Hi!
to recipient— callers writeto:; inside, the value is calledrecipient. The call reads like a sentence: send "Hi!" to Ada._ message—_means no label at the call site.
Swift's API design guidelines favor call sites that read naturally in
English, which is why you see labels like insert(_:at:) and
replacingOccurrences(of:with:).
Default values
func greet(_ name: String, greeting: String = "Hello") -> String {
"\(greeting), \(name)!"
}
print(greet("Ada"))
print(greet("Ada", greeting: "Welcome"))
Hello, Ada!
Welcome, Ada!
Variadic parameters
... after a type accepts any number of values, available inside as
an array:
func average(_ numbers: Double...) -> Double {
guard !numbers.isEmpty else { return 0 }
return numbers.reduce(0, +) / Double(numbers.count)
}
print(average(2, 4, 9))
5.0
In-out parameters
Parameters are constants inside a function. To let a function
change a variable you pass in, mark it inout and call it with &:
func addBonus(to score: inout Int) {
score += 10
}
var myScore = 50
addBonus(to: &myScore)
print(myScore)
60
Use inout sparingly — returning a new value is usually clearer.
Common mistakes
- Trying to change a normal parameter inside a function:
cannot assign to value: 'score' is a 'let' constant. - Passing arguments in the wrong order. Labeled arguments must follow the order the function declares.
Practice
Write formatPrice(_ amount: Double, currency: String = "USD") that
returns a string like "12.5 USD". Call it once with only an amount
and once with currency: "EUR".
Show solution
func formatPrice(_ amount: Double, currency: String = "USD") -> String {
"\(amount) \(currency)"
}
print(formatPrice(12.5))
print(formatPrice(12.5, currency: "EUR"))
12.5 USD
12.5 EUR