Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add default value to inout parameter using Swfit

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?

like image 543
JLau_cy Avatar asked Aug 31 '16 09:08

JLau_cy


2 Answers

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
}
like image 107
Federico Zanetello Avatar answered Sep 26 '22 00:09

Federico Zanetello


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.

like image 37
kelin Avatar answered Sep 23 '22 00:09

kelin