Parameters and Argument Labels
In Sprout you might write log(20, "Read"). Six months later, is 20 minutes, pages or a streak? Swift's parameters come with labels that make calls read like sentences: log(minutes: 20, for: "Read"). Getting the labels right is half of writing Swift that others enjoy using.
The rule
Outside you see the label; inside you use the name.
Each parameter can have two names: an argument label used at the call, and a parameter name used inside the body.
func log(minutes: Int, for habit: String) {
print("Logged \(minutes) min of \(habit)")
}
log(minutes: 20, for: "Read")minuteshas one name, so it serves as both label and parameter name.for habitmeans: callers writefor:, the body sayshabit. (forreads well outside but is a keyword, so it makes a poor name inside.)
Write _ as the label when a label would add nothing:
func double(_ value: Int) -> Int { value * 2 }
double(4) // 8, no label at the callThree more tools:
- Default values let callers skip an argument:
func remind(at hour: Int = 8)can be called asremind()orremind(at: 21). - Variadic parameters accept any number of values as a list:
func total(_ sessions: Int...) -> Intcan be called astotal(10, 15, 5). inoutparameters let a function change the caller's variable. The call marks it with&:bump(&streak).
Parameters are constants inside the body. Assigning to one is an error unless it is inout.
The shortcut
Write the call first, as a sentence, and read the definition off it. markDone("Read", on: today) → the first value needs no label (_ habit: String), the second is labelled on and could be named date inside.
Say the call aloud
"log 20 minutes for Read" →
log(minutes: 20, for: "Read").
Drills
Answer fast — trust the rule.
Given func log(minutes: Int, for habit: String), which call is correct?
Inside that function's body, how do you refer to the habit?
What does _ do in func double(_ value: Int)?
With func remind(at hour: Int = 8), which call is NOT valid?
A function needs to add one to the caller's streak variable itself. What is needed?
Remember
- Outside you see the label; inside you use the name.
- Write the call as a sentence first, then read the definition off it.
_drops a label,= valuesets a default,inoutwith&writes back.
