简体   繁体   English

是否可以创建在Swift中采用“输入”参数的函数数组?

[英]Is it possible to create an array of functions that take “inout” parameters in Swift?

I am running into something that I think might be a bug. 我遇到了我认为可能是错误的问题。 Swift lets you create an array of functions, like this: Swift可让您创建函数数组,如下所示:

func example1(a: Int) {
    println(a)
}

let functionArray1 = [example1]

println(functionArray1[0](3))      // This prints "3"

But if I try to create an array of functions that take an inout parameter, I get the dreaded segmentation fault 11 : 但是,如果我尝试创建带有inout参数的函数数组,则会出现可怕的segmentation fault 11

func example2(inout a: Int) {
    println(a)
}

let functionArray2 = [example2]  // This produces the seg fault

It makes no difference if I actually manipulate a inside the function or not. 这没有什么区别,如果我确实操纵a函数内部与否。

Does anyone know what is going on here? 有人知道这是怎么回事吗? Is there a way to create an array of functions with an inout parameter by using an appropriate type annotation, or some other trick? 有没有一种方法可以通过使用适当的类型注释或其他技巧来创建带有inout参数的函数数组?

EDIT: I have tried providing a type annotation for the array - that does not solve the problem: 编辑:我试图为数组提供类型注释-无法解决问题:

let functionArray2: [(inout Int) -> ()] = [example2]   // Same error...

I have also tried writing the function as a closure (with an explicit type annotation) and then adding the closure to an array, also with no success. 我还尝试过将函数编写为闭包(带有显式类型注释),然后将闭包添加到数组中,但也没有成功。

As the comments on the question have pointed out, this does appear to be a bug relating to Swift's handling of inout in type signatures for some cases. 正如对该问题的评论所指出的那样,在某些情况下,这确实是与Swift处理类型签名中的inout有关的错误。

Until the bug is addressed, you can work around it by using an UnsafeMutablePointer . 在解决该错误之前,您可以使用UnsafeMutablePointer来解决它。

func increment(a: UnsafeMutablePointer<Int>) {
    a.memory += 1
}
let functionArray = [increment]

var thing = 2
functionArray2[0](&thing)
println(thing) // 3

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

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