Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: function with default parameter before non-default parameter

Tags:

swift

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 and use the default value for the first parameter?

like image 898
CarmeloS Avatar asked Jun 08 '14 04:06

CarmeloS


People also ask

Is it possible to give a default value to a function parameter Swift?

Parameters can provide default values to simplify function calls and can be passed as in-out parameters, which modify a passed variable once the function has completed its execution. Every function in Swift has a type, consisting of the function's parameter types and return type.

Can we use default parameter for first parameter in function?

You still need to provide the first parameter regardless of its default value.

Can non default arguments follow default arguments?

The Python "SyntaxError: non-default argument follows default argument" occurs when we define a function with a positional parameter that follows a default parameter. To solve the error, make sure to specify all default parameters after the positional parameters of the function.

What rules apply for functions with default parameters?

Rule 1: creating functions. When programmers give a parameter a default value, they must give default values to all the parameters to right of it in the parameter list.


2 Answers

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.

like image 60
nathan Avatar answered Oct 08 '22 17:10

nathan


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

like image 21
Connor Avatar answered Oct 08 '22 19:10

Connor