如何编写一个函数来返回另一个采用输入输出参数的函数?
我想编写返回 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/