繁体   English   中英

如何在Swift中使用inout参数和Void的返回类型返回函数?

[英]How do I return functions with inout parameters and a return type of Void in Swift?

我试图通过viewController viewDidLoad函数在Xcode 6.0游乐场和iOS项目中运行此代码,在这两种设置下,程序都会使编译器崩溃。 我读过一些关于人们在程序在操场上运行时返回inout函数时遇到类似问题的信息,但是当他们在项目中运行程序时,这个问题就解决了。 我的代码有问题吗?如果是,那是什么问题?或者我在操场或项目中错误地运行了代码?

// testingPlayground
// July 18, 2015


func chooseFunction(isYNegative lessThanZero: Bool) -> (inout Int) -> Void {
    func increaseY(inout #yValue: Int){ // Increases yValue
        yValue += 1
    }

    func decreaseY(inout #yValue: Int){ // Decreases yValue
        yValue -= 1
    }

    return lessThanZero ? increaseY : decreaseY // Returns either the increase or decrease yValue function
}


var yValue = -1
var changeYFunction = chooseFunction(isYNegative: yValue < 0)


while yValue != 0 {
    changeYFunction(&yValue) // Increments/Decrements yValue
}

该代码工作正常,我取出后#从双方的#yValue: Int参数内chooseFunction (具有#将意味着一个参数名称必须给,你不这样做)。

另外,您需要在chooseFunction的返回类型中指定参数名称,并在调用返回的函数时使用它,即:

func chooseFunction(isYNegative lessThanZero: Bool) -> ((inout yValue: Int) -> Void) {

和:

changeYFunction(yValue: &yValue)

换句话说,问题在于您与返回的函数是否要求参数名称不一致。

编辑 :作为另一种选择,您可以考虑重构整个事物,例如,使用简写为咖喱函数:

func stepper(increase increase: Bool)(inout _ y: Int) {
    increase ? ++y : --y
}
var y = -5
let step = stepper(increase: y < 0)
while y != 0 {
    step(&y)
}

实际上,即使以下工作也可以实现,尽管所需的冗长语法使我警惕:

func stepper(increase increase: Bool)(inout _ y: Int)() {
    increase ? ++y : --y
}
var y = -5
let stepY = stepper(increase: y < 0)(&y)
while y != 0 {
    stepY()
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM