2

如何编写一个返回另一个带有 in-out 参数的函数的函数?

我想编写makeIncrementor返回函数的incrementor函数。此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;
           ^

我究竟做错了什么?

4

3 回答 3

1

您正在返回incrementor函数,该函数(inout Int) -> ()在您声明makeIncrementor函数返回类型时具有类型Int -> ()

这种不匹配是您的错误和改变的原因

func makeIncrementor(amount:Int) -> Int-> ()

func makeIncrementor(amount : Int) -> (inout Int) -> ()

是正确的修复。但是,如果您当前尝试在操场上运行该代码,它将崩溃!

我已经在 OSX 和 iOS Xcode 项目中成功运行了以下代码,因此 Xcode 中的 Playground 显然仍然存在一些稳定性问题。

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

var incByTwo = makeIncrementor(2)
var incByThree = makeIncrementor(3)    

var a = 5

println(a) // 5

incByTwo(&a)
println(a) // 7


incByThree(&a)
println(a) // 10 
于 2014-09-18T14:09:50.977 回答
1

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

(为了更清楚地看到它,也将返回值包装makeIncrementor在括号中)

func makeIncrementor(amount:Int) -> ((inout Int) -> Void) {
    func incrementor(inout variable:Int) -> Void {
        variable += amount;
    }
    return incrementor;
}
于 2014-06-21T08:36:38.323 回答
0

如果将返回类型更改为:

func makeIncrementor(amount: Int) -> inout Int -> Void {
    // ...
}

然后错误消失了,但我的 Xcode 崩溃了。

于 2014-06-20T23:07:52.037 回答