Manngo
Manngo

Reputation: 16281

Swift function parameters as local variables

I am learning some of the fine point of Swift. On function parameters, the documentation says:

Function parameters are constants by default.

… and proceeds to discuss in-out parameters, which I suppose are Swift’s version of reference parameters.

In other languages, parameters behave as local variables, so you can do this with impunity:

func test(a: Int) {
    a = a + 1   //  cannot assign to a
    print(a*2)
}
var x = 3
test(x)
print(x)    //  -> 3 as before

I know I can easily create local variables, but is there a Swift equivalent to parameters as local variables?

Note:

The SO description for the parameter tag even uses the word “label”:

Parameters are a type of variable used in a subroutine to refer to the data provided as input to the subroutine.

Upvotes: 0

Views: 1109

Answers (2)

Asperi
Asperi

Reputation: 257573

Not sure I understood what do you try to achieve, but if you want to modify external x (so it would be not 3 as before), then you have to make function parameter as inout:

func test(_ a: inout Int) {
    a = a + 1   //  no error anymore
    print(a*2)
}
var x = 3
test(&x)
print(x)    //  -> 4

demo

Update:

func test(_ a: Int) {
    var a = a // make read-write
    a = a + 1
    print(a*2)
}
var x = 3
test(x)
print(x)    //  -> 3 as before

demo2

Upvotes: 2

Sweeper
Sweeper

Reputation: 270995

Before Swift 3, Swift used to have them. You used to be able to do something like this:

func f(var x: Int) { // note the "var" modifier here
    x += 1
    print(x) // prints 2
}

var a = 1
f(a)
print(a) // prints 1

But it was removed in Swift 3, via SE-0003. The Swift community decided that this is not a good feature. The motivations given in that proposal are:

  • var is often confused with inout in function parameters.
  • var is often confused to make value types have reference semantics.
  • Function parameters are not refutable patterns like in if-, while-, guard-, for-in-, and case statements.

Upvotes: 2

Related Questions