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?
Swift3 answer for passing mutable array pointer.
Function:
Call to function:
In Swift you just add the
var
keyword before the variable name in the function declaration: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).
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.
This can be particularly useful in recursion.
Apple's inout declaration guidelines can be found here.
Solution using Swift3 with Functional Programming...
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 tovar
if you need to alter the value i.e,'var' parameters are deprecated and will be removed in Swift 3. So assigning to a new parameter seems like the best way now:
as mentioned here: 'var' parameters are deprecated and will be removed in Swift 3