5

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?

2

3 Answers 3

6

The two keywords you're talking about, inout and var, are very different.

From Apple Documentation:

In-out parameters are passed as follows:

  1. When the function is called, the value of the argument is copied.
  2. In the body of the function, the copy is modified.
  3. 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
}
3
1

Anyone who needs a default inout parameter may consider such solution:

class SomeType {
    static let singletonInstance = SomeType()

    func someFunction(inout mutableParameter: SomeType) {
        ...
    }

    // Declare function without 'mutableParameter':
    func someFunction() {
        someFunction(SomeType.singletonInstance)
    }
}

When you specify the default value for the parameter, the Swift compiler automatically generates a function without the parameter, for you. In this solution we do it manually.

1

You could create a second function signature to "emulate" a default value

func foo() {
    var v: Int = 0 // your default value
    foo(bar: &v)
}

func foo(bar: inout Int) {
    // do stuff
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.