say I have a function that has non-default parameter after default parameter like this:
func f(first:Int = 100, second:Int){}
how can I call it
If it is a method on a class, you need to call it like this
class Test
{
func f(first:Int = 100, second:Int)
{
println("first is \(first)")
println("second is \(second)")
}
func other()
{
f(second: 4)
f(first: 30, second: 5)
//f(4) will not compile, and neither will f(9,12)
}
}
If the function f is global, you need to call it like this:
f(4)
f(first: 30, 5)
This prints:
first is 100
second is 4
first is 30
second is 5
The current compiler does allow default parameters in the middle of a parameter list.
You can call the function like this if you want to use the default value for the first
parameter:
f(1)
If you want to supply a new value for the first
parameter, use its external name:
f(first: 3, 1)
The documentation explains that parameters with a default value are automatically given an external name:
Swift provides an automatic external name for any defaulted parameter you define, if you do not provide an external name yourself. The automatic external name is the same as the local name, as if you had written a hash symbol before the local name in your code.
On Swift 3:
func defaultParameterBefore(_ x: Int = 1, y: Int ) {}
Calling
defaultParameterBefore(2)
will raise this error
error: missing argument for parameter 'y' in call
The only exception is:
For example:
func defaultParameterBetween(_ x: Int, _ y: Bool = true, _ z: String) {
if y {
print(x)
} else
z()
}
}
// error: missing argument for parameter #3 in call
// defaultParameterWithTrailingClosure(1, { print(0) }
// Trailing closure does work, though.
func defaultParameterWithTrailingClosure(_ x: Int, y: Bool = true,
_ z: () -> Void) {
if y {
print(x)
} else {
z()
}
}
defaultParameterWithTrailingClosure(1) { print(0) }
swift version: DEVELOPMENT-SNAPSHOT-2016-04-12
You should have the default parameters at the end of the parameter list.
func f(second:Int, first:Int = 100){}
f(10)
Place parameters with default values at the end of a function’s parameter list. This ensures that all calls to the function use the same order for their non-default arguments, and makes it clear that the same function is being called in each case.
Documentation link