为什么函数参数在Swift中是不可变的?

时间:2021-12-05 18:00:41

The Swift 3 documentation states that parameters are immutable:

Swift 3文档声明参数是不可变的:

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?

我是否错误地阅读了文档?有这么好的理由吗?

1 个解决方案

#1


5  

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

这里描述的动机如下:https://github.com/apple/swift-evolution/blob/master/proposals/0003-remove-var-parameters.md

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

tl; dr:它避免了与inout关键字的混淆。

#1


5  

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

这里描述的动机如下:https://github.com/apple/swift-evolution/blob/master/proposals/0003-remove-var-parameters.md

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

tl; dr:它避免了与inout关键字的混淆。