Cannot assign to a parameter

拈花ヽ惹草 提交于 2019-12-21 03:13:37

问题


I have declared a function

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?


回答1:


[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;
}

[In Swift < 3.0] Declare the argument with var as in:

func someFunction(var parameterName:Int) {
  parameterName = 2;
  var a = parameterName;
}

use of inout has a different semantics.

[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.

Define variable parameters by prefixing the parameter name with the keyword var: ..."

Excerpt From: Apple Inc. “The Swift Programming Language.”

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



回答2:


In order to modify the argument passed in, you have to designate it as an inout parameter:

func someFunction(inout parameterName:Int)
{
    parameterName = 2;
    var a = parameterName;
}

Note this will change the variable that was passed in as well. If that isn't what you're looking for, use var as GoZoner suggested.



来源:https://stackoverflow.com/questions/25105980/cannot-assign-to-a-parameter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!