Swift Functions and Argument Labels
Use default values and argument labels to make calls readable.
On this page
Swift basics.
- Use default values and argument labels to make calls readable.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
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.
Code example
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))Hi Ada! Hi Bo! Hi Bo!
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
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))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! |
Behind the scenes
How Swift processes this code
Swift compiles the program; its top-level statements run in source order.
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.