Swift 4编程语言,inout参数不适用于FunctionType作为Paramter

Vis*_*bhu 6 swift swift-playground swift4

这是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(&currentValue))
print(currentValue)
Run Code Online (Sandbox Code Playgroud)

实际输出2 3

预期产出2 2

因为CurrentValue不是很重要.将currentValue作为3传递最初使用stepBackward()方法打印值2

我想在减量后保持价值.

但是这里没有维持currentValue.

小智 3

这是因为在应用算术之后,您实际上并没有为参数赋值,您只是返回新值而不分配它。尝试下面的代码

//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(&currentValue))
print(currentValue)
Run Code Online (Sandbox Code Playgroud)