kennysong
kennysong

Reputation: 2124

Why are function parameters immutable in Swift?

The Swift 3 documentation states that parameters are immutable:

Function parameters are constants by default.

It also states that value types are copied when passed into functions:

Strings, arrays, and dictionaries are copied when they are passed to a function or method.

So, why are parameters both immutable and copied? If the argument is a constant, then we don't need a copy of its value in the function's scope. If the argument is copied, then the original variable passed in cannot be modified in the function (for value types).

Moreover, immutability seems inconvenient as we can't make local changes to an argument without first explicitly copying it (once again) to a local variable.

Am I reading the documentation incorrectly? Is there a good reason why this is the case?

Upvotes: 11

Views: 2860

Answers (1)

ganzogo
ganzogo

Reputation: 2614

The motivation for this is described here: https://github.com/apple/swift-evolution/blob/master/proposals/0003-remove-var-parameters.md

tl;dr: it avoids confusion with the inout keyword.

Upvotes: 7

Related Questions