Logo 61e73bc61c0e1780102320e879dc3cac0e29303ea8894dd8f10c942f3ba8120f

otters.io

An adorable little blog

Mighty Morphin Mutable Parameters

Monday — April 18th, 2016

Power rangers

I mentioned using var and inout in Swift function parameters and I thought I should give a small example of using them. Heads up, before you fall in love, Swift 2.2 will warn you that var is preparing for the great beyond. ☠️ Swift 3 will remove the var parameter annotation altogether. The inout parameter annotation is here to stay.

By default, you cannot modify a parameter passed into a Swift function. They are immutable and the compiler will gently remind you of that.

Immutable error

For example, the compiler won't let you do this:

func addMilk(shoppingList: String) {
    shoppingList.append("Milk")
}

If you annotate a function parameter with var you are allowed to modify a copy of the parameters passed in but you don't get those changes back afterwards.

So the compiler is ok with this:

func addMilk(var shoppingList: String) {
    shoppingList.append("Milk")
}

var myShoppingList = ["Cheese", "Eggs"]
addMilk(myShoppingList)

but when you ask for myShoppingList later you get:

["Cheese", "Eggs"]

Because only a copy of that parameter existed within the function. If you wanted to get those back when you were done you could use the inout parameter annotation like this:

func addMilk(inout shoppingList: String) {
    shoppingList.append("Milk")
}

var myShoppingList = ["Cheese", "Eggs"]
addMilk(myShoppingList)

Now when you ask for myShoppingList you'll get:

["Cheese", "Eggs", "Milk"]

Be careful though! Swift encourages immutability wherever possible for a reason, but when you have no better option, inout has your back. 👍