Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are function parameters immutable in Swift?

Tags:

swift

swift3

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?

like image 233
kennysong Avatar asked Oct 26 '16 17:10

kennysong


1 Answers

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.

like image 114
ganzogo Avatar answered Nov 14 '22 14:11

ganzogo