Swift 4 编程语言,inout 参数不适用于函数类型作为参数

标签 swift swift4 swift-playground

这是 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(&currentValue))
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(&currentValue))
print(currentValue)

关于Swift 4 编程语言,inout 参数不适用于函数类型作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51510687/

相关文章:

swift - Swift 关系中的 Realm 不添加行

swift - 可以访问带问号而不带感叹号的可选变量吗?

ios - 如何通过 AlertView 执行 segue 切换到另一个 ViewController?

swift - 如何在 firebase swift 4 中使用 childByAutoId 获取自动生成的数字

Swift 在 println 的控制台中给我一条错误消息

ios - Swift:如何在中断时停止调用 scheduleBuffer 完成处理程序?

ios - UIcollectionview 更新单元格高度

swift - Xcode 9.2 没有显示 Swift 4.1

ios - Xcode 6 Beta 5 swift Playground : Cannot find symbol for CGRectMake()

ios - 为什么我在 Swift playground 中进行简单的加法操作时会出错?