Swift make method parameter mutable?

无人久伴 提交于 2019-11-28 04:26:38

As stated in other answers, as of Swift 3 placing var before a variable has been deprecated. Though not stated in other answers is the ability to declare an inout parameter. Think: passing in a pointer.

func reduceToZero(_ x: inout Int) {
    while (x != 0) {
        x = x-1     
    }
}

var a = 3
reduceToZero(&a)
print(a) // will print '0'

This can be particularly useful in recursion.

Apple's inout declaration guidelines can be found here.

LML

For Swift 1 and 2 (for Swift 3 see answer by achi using an inout parameter): Argument of a function in Swift is let by default so change it to var if you need to alter the value i.e,

func reduceToZero(var x:Int) -> Int {
    while (x != 0) {
        x = x-1     
    }
    return x
}
GeRyCh

'var' parameters are deprecated and will be removed in Swift 3. So assigning to a new parameter seems like the best way now:

func reduceToZero(x:Int) -> Int {
    var x = x
    while (x != 0) {
        x = x-1            
    }
    return x
}

as mentioned here: 'var' parameters are deprecated and will be removed in Swift 3

Swift3 answer for passing mutable array pointer.

Function:

func foo(array: inout Array<Int>) {
    array.append(1)
}

Call to function:

var a = Array<Int>()
foo(array:&a)

In Swift you just add the var keyword before the variable name in the function declaration:

func reduceToZero(var x:Int) -> Int { // notice the "var" keyword
    while (x != 0) {
        x = x-1            
    }
    return x
}

Refer to the subsection "Constant and Variable Parameters" in the "Functions" chapter of the Swift book (page 210 of the iBook as it is today).

Solution using Swift3 with Functional Programming...

func reduceToZeroFP(x:Int) -> Int {
    while (x > 0) {
        return reduceToZeroFP(x: x-1)
    }
    return x
}

There are some cases where we dont ned to use inout

We can use something like this if you want that changes/scope to be only inside the function:

func manipulateData(a: Int) -> Int {
    var a = a
    // ...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!