Swift:返回一个 In-Out 函数

标签 swift swift-playground

如何编写一个函数来返回另一个采用输入输出参数的函数?

我想编写返回 incrementor 函数的函数 makeIncrementor。此 incrementor 函数采用一个 In-Out 参数并将其递增一定量(它不返回任何内容)。这是我的代码:

func makeIncrementor(amount:Int) -> Int->Void {
    func incrementor(inout variable:Int) -> Void {
        variable += amount;
    }
    return incrementor;
}

var x = 1;
var inc = makeIncrementor(2);
inc(&x)
//x should now contain 3

但是,Xcode 给出以下错误:

<REPL>:9:12: error: 'Int' is not a subtype of 'inout Int'
    return incrementor;
           ^

我做错了什么?

最佳答案

要返回的函数的参数列表应括在括号中,并且应在要修改的参数之前包含 inout,例如

(为了看得更清楚,请将 makeIncrementor 的返回值也包含在括号中)

func makeIncrementor(amount:Int) -> ((inout Int) -> Void) {
    func incrementor(inout variable:Int) -> Void {
        variable += amount;
    }
    return incrementor;
}

关于Swift:返回一个 In-Out 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24336838/

相关文章:

swift - 为什么 Swift playground 显示错误的执行次数?

arrays - 在接收函数返回数组时执行错误的过量操作?

xcode - 尝试在 Swift 的多点连接测试应用程序中使用 NSNotification

ios - 通过应用内购买去除广告时,此功能是否无法识别我的 key ?

swift - 为什么 MyStack 不符合 ProtoStack 的任何想法?

ios - 将 Parse 导入 Xcode 项目

swift - 如何使用 Swift Playground 中的更新功能

arrays - Swift 3 中数组平衡点的公共(public)函数

swift - 在 Playground 中测试委托(delegate)给 'nil'

ios - 无法声明对泛型类的引用