无法分配参数 [英] Cannot assign to a parameter
问题描述
我声明了一个函数
func someFunction(parameterName: Int) {
parameterName = 2 //Cannot assign to let value parameter Name
var a = parameterName
}
并尝试在运行时给它分配一个值,但它给了我错误
无法分配给值参数名称。
and trying to assign it a value during runtime, but it gives me error "Cannot assign to let value parameter Name".
默认情况下参数名是否为常量?我可以将其更改为变量吗?
Is the parameter name constant by default? Can I change it to a variable?
推荐答案
[在Swift> = 3.0] 函数参数是定义为如果通过让
,因此是常量。如果要修改参数,则需要局部变量。因此:
[In Swift >= 3.0] Function parameters are defined as if by let
and thus are constants. You'll need a local variable if you intend to modify the parameter. As such:
func someFunction (parameterName:Int) {
var localParameterName = parameterName
// Now use localParameterName
localParameterName = 2;
var a = localParameterName;
}
[在Swift< 3.0] 用 var
声明参数,如下所示:
[In Swift < 3.0] Declare the argument with var
as in:
func someFunction(var parameterName:Int) {
parameterName = 2;
var a = parameterName;
}
使用 inout
有不同的语义。
[请注意,变量参数将在未来的Swift版本中消失。]以下是关于变量参数的Swift文档:
[Note that "variable parameters" will disappear in a future Swift version.] Here is the Swift documentation on "variable parameters":
默认情况下,函数参数是常量。尝试从该函数
的主体内更改函数参数的
值会导致编译时错误。这意味着您无法错误地更改参数的
值。
Function parameters are constants by default. Trying to change the value of a function parameter from within the body of that function results in a compile-time error. This means that you can’t change the value of a parameter by mistake.
但是,有时函数有一个变量的变量是有用的要使用的参数值。您可以通过将一个或多个
参数指定为变量参数来避免在函数内自己定义
新变量。变量参数是
可用作变量而不是常量,并为函数提供一个新的
可修改参数值的副本,使用
。
However, sometimes it is useful for a function to have a variable copy of a parameter’s value to work with. You can avoid defining a new variable yourself within the function by specifying one or more parameters as variable parameters instead. Variable parameters are available as variables rather than as constants, and give a new modifiable copy of the parameter’s value for your function to work with.
通过在参数名前加上关键字var:...前缀来定义变量参数。
Define variable parameters by prefixing the parameter name with the keyword var: ..."
摘录自:Apple Inc Swift编程语言。
Excerpt From: Apple Inc. "The Swift Programming Language."
如果你真的想要改变存储在传递给函数的位置的值,那么,正如@conner所说, inout
参数是合理的。以下是[在Swift> = 3.0 ]中的示例:
If you actually want to change the value stored in a location that is passed into a function, then, as @conner noted, an inout
parameter is justified. Here is an example of that [In Swift >= 3.0]:
1> var aValue : Int = 1
aValue: Int = 1
2> func doubleIntoRef (place: inout Int) { place = 2 * place }
3> doubleIntoRef (&aValue)
4> aValue
$R0: Int = 2
5> doubleIntoRef (&aValue)
6> aValue
$R1: Int = 4
这篇关于无法分配参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!