我正在阅读文档,想尝试"inout";参数,但它似乎没有按我的意愿工作。我做错了什么?
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
您可以使用一个额外的var来传递数组,而不需要像使用inout那样从numbersInPow
方法返回数组。
修改类似的功能
func numbersInPow(numbers: inout [Int], powerBy: Int){
numbers = numbers.map { Int(pow(Double($0), Double(powerBy))) }
}
并使用
var arr = [1, 2, 3, 4, 5]
numbersInPow(numbers: &arr, powerBy: 6)
print(arr) // Output : [1, 64, 729, 4096, 15625]
错误sasyCannot pass immutable value as inout argument: implicit conversion from '' to '' requires a temporary
。在函数numbersInPow
中,Swift认为&[1, 2, 3, 4, 5]
是常量——它的意思是let
。给一个输入输出参数一个常数是没有意义的,因为不能改变。
所以你必须像一样修改它
var arr = [1, 2, 3, 4, 5]
print(numbersInPow(numbers: &arr, powerBy: 6))