Swift Functions and Argument Labels
Use default values and argument labels to make calls readable.
Swift
func greet(_ name: String, times: Int = 1) -> String {
return Array(repeating: "Hi \(name)!", count: times).joined(separator: " ")
}
print(greet("Ada"))
print(greet("Bo", times: 2))Output
Hi Ada! Hi Bo! Hi Bo!
Explanation
A Swift function declares each parameter with an optional argument label, a name, and a type. The underscore in _ name removes the label for the first parameter, while times keeps its label, so callers write greet("Bo", times: 2).
A default value such as times: Int = 1 makes the argument optional. The function builds an array with Array(repeating:count:) and joins it with a separator, so no trailing space is left over.
Explore the dry run
Guided walkthroughReady
1
func greet(_ name: String, times: Int = 1) -> String {2
return Array(repeating: "Hi \(name)!", count: times).joined(separator: " ")3
}4
5
print(greet("Ada"))6
print(greet("Bo", times: 2))Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| The first argument has no label; times defaults to 1. | — | — | |
| times is 1, so one greeting is produced. | name = "Ada", times = 1 | Hi Ada! | |
| Two copies are joined by a space. | name = "Bo", times = 2 | Hi Ada! Hi Bo! Hi Bo! |
Cost and common mistakes
O(times) time and space.
- Omitting a required argument label, as in greet("Bo", 2), is a compile error.
- A negative count passed to Array(repeating:count:) crashes at runtime.
Try it yourself
Predict greet("Cy", times: 0).
Reveal answer and reasoning
It returns an empty string, so print writes an empty line.