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

Posted

技术标签:

【中文标题】Swift 4 编程语言,输入参数不适用于函数类型作为参数【英文标题】:Swift 4 Programming Language, inout parameter is not working for FunctionType as Paramter 【发布时间】:2018-07-25 04:15:12 【问题描述】:

这是来自 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。

【问题讨论】:

我认为,Apple 文档需要更正。 @Kamran 实际上,OP 没有尝试文档中的确切示例。相反,他试图通过自己修改的示例来理解inout 的概念。 @Vishnu 如果您没有真正更改函数内参数的值,那么使用参数作为inout 有什么意义? @nayem 是的,实际上在该示例中没有使用inout,因为它是为了演示如何返回函数类型。所以它可能会让新手感到困惑。 @nayem,感谢指出错误,输入值没有改变是我的错误,只是学习新的。接受下面的答案。 【参考方案1】:

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

//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)

【讨论】:

【参考方案2】:

您可以尝试不退货。只需在函数中传递当前值并更新该值,它将自动更新当前值。

func stepForward(_ input: inout Int)   
  input = input + 1


func stepBackward(_ input: inout Int)  
   input = input - 1


func chooseStepFunction(backward: Bool, currentValue: inout Int)   
   backward ? stepBackward(&currentValue) : stepForward(&currentValue)


var currentValue = 3
chooseStepFunction(backward: currentValue > 0, currentValue: &currentValue)
print(currentValue)

【讨论】:

【参考方案3】:

您的问题是您从未更改过 currentValue 值!

您应该在 chooseStepFuction 方法中更改 currentValue 值!

chooseStepFunction(backward: currentValue > 0,
                   currentValue: &currentValue)

【讨论】:

以上是关于Swift 4 编程语言,输入参数不适用于函数类型作为参数的主要内容,如果未能解决你的问题,请参考以下文章

SWIG 多参数类型映射适用于函数,但如果有多个构造函数,则不适用于构造函数

Xcode 8.3.2 不适用于 Alamofire 4.4.0

C语言调用Swift方法并传参数

隐式类型转换不适用于方法参数?

4 .Swift函数|闭包

type 类型的 Spark reduceByKey(arguments) 不适用于参数 arguments