Swift Tutorial · Swift Basics · Lesson 9 of 30
Swift Functions
Declare functions with argument labels, default values, variadic and inout parameters, and multiple returns.
Argument labels
Each parameter has an argument label used at the call site and a parameter name used inside. Write
_ to omit the label. Good labels make calls read like sentences: move(from: a, to: b).
func greet(_ name: String, from city: String) -> String {
"Hello \(name) from \(city)!"
}
func square(_ x: Int) -> Int { x * x }
print(greet("Ana", from: "Lisbon"))
print(square(9))
Output
Hello Ana from Lisbon! 81
Run this on your computer — see “Get Started” for setup.
Defaults, variadics and inout
Parameters can have default values; Int... accepts any number of values; inout lets a function change a
caller's variable (passed with &). A single-expression function body doesn't need return.
import Foundation
func formatPrice(_ amount: Double, currency: String = "EUR", decimals: Int = 2) -> String {
String(format: "%.\(decimals)f %@", amount, currency)
}
func average(_ numbers: Double...) -> Double {
numbers.isEmpty ? 0 : numbers.reduce(0, +) / Double(numbers.count)
}
func applyDiscount(to price: inout Double, percent: Double) {
price -= price * percent / 100
}
print(formatPrice(9.5))
print(formatPrice(9.5, currency: "USD", decimals: 0))
print(average(2, 4, 9))
var price = 80.0
applyDiscount(to: &price, percent: 25)
print(price)
Output
9.50 EUR 10 USD 5.0 60.0
Run this on your computer — see “Get Started” for setup.
Test yourself
What does _ before a parameter name mean?
The parameter is unusedThe caller passes the argument without a labelThe parameter is optionalThe parameter is private
Show answer
Answer: The caller passes the argument without a label