Functions and Closures
Argument Labels
Swift argument labels make function calls read like short phrases.
Name the call-site meaning
argument_labels.swift
Replay: real traced execution (multi-file project)
func makeLabel(for item: String, count: Int) -> String {
return "\(item): \(count)"
}
let count = 3
let label = makeLabel(for: "tickets", count: count)
print(label)
func makeLabel(for item: String, count: Int) -> String {
return "\(item): \(count)"
}
let count = 1
let label = makeLabel(for: "tickets", count: count)
print(label)
func makeLabel(for item: String, count: Int) -> String {
return "\(item): \(count)"
}
let count = 5
let label = makeLabel(for: "tickets", count: count)
print(label)
count ← 3
5let count→ 3 = 3 //@count=1, 56let label = makeLabel(for: "tickets", count: count3)func makeLabel(for item: String, count: Int) -> String
1func makeLabel(for itemtickets: String, count3: Int) -> String {2 return "\(itemtickets): \(count3)"3}label ← tickets: 3
5let count = 3 //@count=1, 56let label→ tickets: 3 = makeLabel(for: "tickets", count: count3)78print(labeltickets: 3)outputtickets: 3
count ← 1
5let count→ 1 = 16let label = makeLabel(for: "tickets", count: count1)func makeLabel(for item: String, count: Int) -> String
1func makeLabel(for itemtickets: String, count1: Int) -> String {2 return "\(itemtickets): \(count1)"3}label ← tickets: 1
5let count = 16let label→ tickets: 1 = makeLabel(for: "tickets", count: count1)78print(labeltickets: 1)outputtickets: 1
count ← 5
5let count→ 5 = 56let label = makeLabel(for: "tickets", count: count5)func makeLabel(for item: String, count: Int) -> String
1func makeLabel(for itemtickets: String, count5: Int) -> String {2 return "\(itemtickets): \(count5)"3}label ← tickets: 5
5let count = 56let label→ tickets: 5 = makeLabel(for: "tickets", count: count5)78print(labeltickets: 5)outputtickets: 5
Follow the Call
countstarts as3.- The call is
makeLabel(for: "tickets", count: count). - The function uses the item text
tickets. - It combines the item with the count.
- The program prints
tickets: 3. | count | label text | | --- | --- | | 3 | tickets: 3 | | 1 | tickets: 1 | | 5 | tickets: 5 |
labels
The external label appears at the call site, while the parameter name is used inside the function body.
Exercise: argument_labels.swift
Reproduce tickets: 3, then use the pinned count variants 1 and 5 to predict tickets: 1 and tickets: 5.