Functions in Swift
Declaring functions, parameter labels, default values, and returning multiple values with tuples.
2 min de lectura
Functions in Swift are declared with func, and Swift's parameter system has a feature most languages don't: every parameter can have both an argument label (used at the call site) and a parameter name (used inside the function body).
func greet(name: String) -> String {
return "Hello, \(name)!"
}
print(greet(name: "Ada")) // "Hello, Ada!"By default, the parameter name doubles as the label, so you write name: at the call site. That reads naturally for a single obvious parameter, but starts to feel redundant for something more conversational.
Custom argument labels
You can give a parameter a different label for callers than the name used internally — this is what makes well-written Swift function calls read almost like a sentence:
func greet(person name: String, warmly isWarm: Bool) -> String {
return isWarm ? "Hey \(name)!! So great to see you!" : "Hello, \(name)."
}
print(greet(person: "Sam", warmly: true))Here, callers write person: and warmly:, but inside the function you use name and isWarm. Use _ as the label to drop it entirely when it would just be noise:
func square(_ number: Int) -> Int {
return number * number
}
print(square(5)) // no label needed — square(number: 5) would be redundantDefault parameter values
func greet(name: String, greeting: String = "Hello") -> String {
return "\(greeting), \(name)!"
}
print(greet(name: "Grace")) // "Hello, Grace!"
print(greet(name: "Grace", greeting: "Hi")) // "Hi, Grace!"A default value means callers only need to supply it when they want something other than the common case — reducing the number of near-duplicate function overloads you'd otherwise need.
Returning multiple values with tuples
Swift functions can return more than one value at once using a tuple, without needing to define a custom type just to bundle them:
func minMax(of numbers: [Int]) -> (min: Int, max: Int)? {
guard let first = numbers.first else { return nil }
var currentMin = first
var currentMax = first
for number in numbers {
if number < currentMin { currentMin = number }
if number > currentMax { currentMax = number }
}
return (currentMin, currentMax)
}
if let result = minMax(of: [8, 3, 15, 4]) {
print("Min: \(result.min), Max: \(result.max)") // "Min: 3, Max: 15"
}Notice the return type is (min: Int, max: Int)? — an optional tuple, since an empty array has no min or max. Naming the tuple's members (min:, max:) lets callers access result.min and result.max instead of the less readable result.0 and result.1.
Functions are the backbone of organizing Swift code — the next lesson builds on them with closures, functions that can be passed around and stored just like any other value.