Swift - Function Default Parameter Values

Introduction

You can assign a default value to a parameter so that it becomes optional when you are calling it.

Consider the following function in which you have three parameters:

func joinName(firstName:String,
              lastName:String,
              joiner:String = " " ) -> String {
     return "\(firstName)\(joiner)\(lastName)"
}

The third parameter has a default value of a single space.

When calling this function with three arguments, you need to specify the default parameter name, like this:

Demo

var fullName = joinName("first", "second", joiner :",")
print(fullName)

For default parameters, you need to specify the parameter name explicitly when calling the function.

For a default parameter, there is no need to specify an external parameter name or use the # shorthand when defining the function, as the default parameter implicitly indicates a named argument.

You can omit the default parameter when calling the function and it will use the default value of the single space for the third argument:

var fullName = joinName("first","second")
print(fullName)   //hi

Parameters with a default value must always be placed at the end of the parameter list.

Be careful when defining functions of the same name but with different input parameters.

Consider the following two functions:

func joinName(firstName:String,
              lastName:String,
              joiner:String = " ") -> String {
     return "\(firstName)\(joiner)\(lastName)"
}
func joinName(firstName:String,
               lastName:String) -> String {
     return "\(firstName)\(lastName)"
}

To call the first function, you need to specify the external parameter name for the default parameter, like this:

var fullName = joinName("first", "last", joiner:",")
print(fullName)  

If you now call joinName by passing only two arguments, it will result in a compilation error because the compiler is not able to resolve which function to call:

var fullName = joinName("first","last")

Related Topic