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

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

概述这是 swift文档中的示例代码.我正在学习快速的语言,我看到函数类型作为参数,示例代码没有inout关键字.但我试图使用这个与inout参数,但下面的示例没有按预期工作. https://docs.swift.org/swift-book/LanguageGuide/Functions.html(函数类型作为返回类型) //Function Types as Return Typesfunc 这是 swift文档中的示例代码.我正在学习快速的语言,我看到函数类型作为参数,示例代码没有inout关键字.但我试图使用这个与inout参数,但下面的示例没有按预期工作.

https://docs.swift.org/swift-book/LanguageGuide/Functions.html(函数类型作为返回类型)

//Function Types as Return Typesfunc 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 = 3let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)print(moveNearerToZero(&currentValue))print(currentValue)

实际输出
    2
    3

预期产出
    2
    2

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

我想在减量后保持价值.

但是这里没有维持currentValue.

解决方法 这是因为在应用算术之后你实际上并没有为参数赋值,而是只返回新值而不指定它.请尝试以下代码

//Function Types as Return Typesfunc 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 = 3let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)print(moveNearerToZero(&currentValue))print(currentValue)
总结

以上是内存溢出为你收集整理的Swift 4编程语言,inout参数不适用于FunctionType作为Paramter全部内容,希望文章能够帮你解决Swift 4编程语言,inout参数不适用于FunctionType作为Paramter所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1018450.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存