简体   繁体   English

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

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

I have attempted to run this code in an Xcode 6.0 playground and in an iOS project through the viewController viewDidLoad function, and in both settings the program crashes the compiler. 我试图通过viewController viewDidLoad函数在Xcode 6.0游乐场和iOS项目中运行此代码,在这两种设置下,程序都会使编译器崩溃。 I have read about people having similar issues when returning inout functions when the program is run through a playground, however the issue was resolved when they ran their program through a project. 我读过一些关于人们在程序在操场上运行时返回inout函数时遇到类似问题的信息,但是当他们在项目中运行程序时,这个问题就解决了。 Is something incorrect with my code, and if so what is wrong, or am I running the code incorrectly in the playground or project? 我的代码有问题吗?如果是,那是什么问题?或者我在操场或项目中错误地运行了代码?

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

The code works fine for me after removing the # from both of the #yValue: Int parameters inside chooseFunction (having the # would imply that an argument name must be given, which you don't do). 该代码工作正常,我取出后#从双方的#yValue: Int参数内chooseFunction (具有#将意味着一个参数名称必须给,你不这样做)。

Alternatively, you need to specify the parameter name in the return type of chooseFunction and use it when you call the returned function, ie: 另外,您需要在chooseFunction的返回类型中指定参数名称,并在调用返回的函数时使用它,即:

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

And: 和:

changeYFunction(yValue: &yValue)

In other words, the problem is that you are not consistent with whether or not the returned functions require a name for the argument or not. 换句话说,问题在于您与返回的函数是否要求参数名称不一致。

edit : As yet another alternative, you could consider refactoring the whole thing, eg, use the shorthand for curried functions: 编辑 :作为另一种选择,您可以考虑重构整个事物,例如,使用简写为咖喱函数:

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

In fact, even the following works, although the hairy syntax required makes me wary: 实际上,即使以下工作也可以实现,尽管所需的冗长语法使我警惕:

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