I was reading the docs and wanted to try "inout" parameter in my function, but it doesn't seem to work as I want it to. What am I doing wrong?
func numbersInPow(numbers: inout [Int], powerBy: Int) -> [Int] {
return numbers.forEach { Int(pow(Double($0), Double(powerBy))) //error
}
print(numbersInPow(numbers: &[1, 2, 3, 4, 5], powerBy: 6)) //doesnt let me to pass int array in here
CodePudding user response:
You can use one extra var to pass the array and no need to return an array from numbersInPow
method as you are using inout.
Modify the function like this
func numbersInPow(numbers: inout [Int], powerBy: Int){
numbers = numbers.map { Int(pow(Double($0), Double(powerBy))) }
}
And Use
var arr = [1, 2, 3, 4, 5]
numbersInPow(numbers: &arr, powerBy: 6)
print(arr) // Output : [1, 64, 729, 4096, 15625]
CodePudding user response:
The error sasy Cannot pass immutable value as inout argument: implicit conversion from '' to '' requires a temporary
. In your function numbersInPow
Swift thinks that &[1, 2, 3, 4, 5]
is constants - it means let
. So you must modify it like
var arr = [1, 2, 3, 4, 5]
print(numbersInPow(numbers: &arr, powerBy: 6))