Swift make method parameter mutable?

后端 未结 7 845
滥情空心
滥情空心 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:35

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

提交回复
热议问题