Swift make method parameter mutable?
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 = 3reduceToZero(&a)print(a) // will print '0'
This can be particularly useful in recursion.
Apple's inout
declaration guidelines can be found here.
'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
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 valuei.e,
func reduceToZero(var x:Int) -> Int { while (x != 0) { x = x-1 } return x}