这是 swift 文档中的示例代码。我正在学习swift语言,我看到函数类型作为参数,示例代码没有inout关键字。但是我试图将它与 inout 参数一起使用,但下面的示例没有按预期工作。
https://docs.swift.org/swift-book/LanguageGuide/Functions.html (函数类型作为返回类型)
//Function Types as Return Types
func stepForward(_ input: inout Int) -> Int {
return input + 1
}
func stepBackward(_ input: inout Int) -> Int {
return input - 1
}
func chooseStepFunction(backward: Bool) -> (inout Int) -> Int {
let a = backward ? stepBackward : stepForward
return a
}
var currentValue = 3
let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)
print(moveNearerToZero(¤tValue))
print(currentValue)
实际输出 2个 3
预期输出 2个 2
因为 CurrentValue 是 inout 参数。将 currentValue 作为 3 传递最初使用 stepBackward() 方法打印值 2
我想在递减后保持这个值。
但是这里不维护currentValue。
最佳答案
那是因为在应用算术之后你实际上并没有给参数赋值,你只是返回新值而不赋值。试试下面的代码
//Function Types as Return Types
func stepForward(_ input: inout Int) -> Int {
input += 1
return input
}
func stepBackward(_ input: inout Int) -> Int {
input -= 1
return input
}
func chooseStepFunction(backward: Bool) -> (inout Int) -> Int {
let a = backward ? stepBackward : stepForward
return a
}
var currentValue = 3
let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)
print(moveNearerToZero(¤tValue))
print(currentValue)
关于Swift 4 编程语言,inout 参数不适用于函数类型作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51510687/