Swift make method parameter mutable?

后端 未结 7 829
滥情空心
滥情空心 2020-12-07 17:04

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

func reduceToZero(x:Int) -> Int {
    while (x != 0) {
        x = x-1            //         


        
7条回答
  •  [愿得一人]
    2020-12-07 17:38

    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
    }
    

提交回复
热议问题