Jun 24, 2014

Swift seems nice, but cannot write simple function such as converting array to UnsafePointer

I'm writing an iOS accelerated framework application with Swift and it's frequently necessary to convert Swift array to unsafe pointer. However the conversion function I wrote cannot be compiled. Does anybody know what's wrong with this function?
func aryToUnsafePointer<T>(ary:T[]) -> UnsafePointer<T> {
    return UnsafePointer<T>((&ary as CMutablePointer<T>).value)
}
The error is
'T[]' is not a subtype of '@lvalue $T1'

problem solved

thanks to Justin

It is not allowed to take "&" of argument directly, so changing function like this will work.

func aryToUnsafePointer<T>(ary:T[]) -> UnsafePointer<T> {
    var a = ary
    return UnsafePointer<T>((&a as CMutablePointer<T>).value)
}

Now I understand the reason, but it seems a bit odd to me, though.

2 comments:

Justin said...

I think this might be your solution:
https://devforums.apple.com/message/981367#981367

Tomo Iida said...

> Justin

Thanks for the link! Copying argument to local variable solved the problem.