Swift Default Parameters
A default parameter is a parameter that carries a ready value in its definition. A call can skip that argument and the ready value fills in.
Calling with and without the argument
The punct parameter carries a default value in the definition. The first call skips that argument and the second call passes a question mark.
func greet(name: String, punct: String = "!") -> String {
return "Hello, " + name + punct
}
print(greet(name: "Ana"))
print(greet(name: "Ana", punct: "?"))Dropping a label with an underscore
An underscore stands before each parameter name here. The call passes both values with no labels at all.
func add(_ a: Int, _ b: Int) -> Int {
return a + b
}
print(add(2, 3))Mixing labelled and unlabelled parameters
The first parameter drops its label with an underscore. The second parameter keeps its label at the call site.
func repeatWord(_ word: String, times: Int) -> String {
var text = ""
for _ in 1...times {
text = text + word
}
return text
}
print(repeatWord("ha", times: 3))Two defaults at once
Both parameters carry defaults in this definition. Each call fills in only the arguments it passes.
func box(width: Int = 10, height: Int = 4) -> Int {
return width * height
}
print(box())
print(box(width: 3))
print(box(width: 3, height: 3))Example
func ticket(name: String, seat: String = "General") -> String {
return name + " sits in " + seat
}
print(ticket(name: "Ana"))
print(ticket(name: "Bo", seat: "Front"))Key points
- A default value sits after an equals sign in the parameter list.
- A call that passes the argument uses the passed value.
- A parameter with no default still needs an argument in every call.
- An underscore before a parameter name drops its label at call sites.
- One function can mix a labelled parameter and an unlabelled parameter.
In this example, the ticket function gives seat a default value of General. The first call passes only a name and prints Ana sits in General. The second call passes Front as the seat and prints Bo sits in Front.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Swift Compiler
Exercise
What happens when a call skips an argument that has a default value?