In Swift 2 it is possible to do the following:
class SomeType {
static let singletonInstance = SomeType()
func someFunction(var mutableParameter: SomeType = SomeType.singletonInstance) {
...
}
}
However in Swift 3 the var
keyword will be removed for function parameters in favour of inout
. I have not been able to achieve the same result as the above using the inout
keyword.
class SomeType {
static let singletonInstance = SomeType()
func someFunction(inout mutableParameter: SomeType = SomeType.singletonInstance) {
...
}
}
Instead I receive an error of "Default argument value of type 'SomeType' cannot be converted to type 'inout SomeType'"
My question is whether it is possible to use inout
with default value?
The two keywords you're talking about, inout
and var
, are very different.
From Apple Documentation:
In-out
parameters are passed as follows:
- When the function is called, the value of the argument is copied.
- In the body of the function, the copy is modified.
- When the function returns, the copy’s value is assigned to the original argument.
Therefore you can't give a default value to an inout
parameter, as it would make the inout
property completely useless.
What you can do is receive a normal (constant) parameter with a default value, and declare a new var
with the same name this way (code from the Swift Evolution's Removing var from Function Parameters Proposal, with the addition of the default parameter):
func foo(i: Int = 5) {
var i = i
// now you can change i as you'd like
}