Swift make method parameter mutable?

How can I deal with this error without creating additional variable?

func reduceToZero(x:Int) -> Int {
    while (x != 0) {
        x = x-1            // ERROR: cannot assign to 'let' value 'x'
    }
    return x
}

I don't want to create additional variable just to store the value of x. Is it even possible to do what I want?


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.


对于Swift 1和Swift 3(对于Swift 3,请参阅achi使用inout参数的答案):Swift中的函数参数默认为let ,如果需要更改值,则将其更改为var

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

'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

链接地址: http://www.djcxy.com/p/20796.html

上一篇: 包含一组固定可变对象的对象是否可变?

下一篇: Swift使方法参数可变?