Swift: function with default parameter before non-default parameter

Solution 1:

The current compiler does allow default parameters in the middle of a parameter list.

screenshot of Playground

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.

Solution 2:

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

Solution 3:

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:

  • There is a parameter before the default parameter;
  • and the parameter after the default parameter is a closure;
  • and the closure parameter is the last parametr;
  • and calling via trailing closure

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