I am running into something that I think might be a bug. Swift lets you create an array of functions, like this:
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
:
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.
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?
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.
Until the bug is addressed, you can work around it by using an UnsafeMutablePointer
.
func increment(a: UnsafeMutablePointer<Int>) {
a.memory += 1
}
let functionArray = [increment]
var thing = 2
functionArray2[0](&thing)
println(thing) // 3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.