Kelvin Lau Kelvin Lau - 5 months ago 6
Swift Question

Interoperating with C pointer to an Int array in Swift

I've got a legacy codebase with this function:

-(void)foo: (int *)buffer {
myArray[0] = buffer[0];
myArray[1] = buffer[1];
myArray[2] = buffer[2];
myArray[3] = buffer[3];
}


In Swift, this method is written as the following:

func foo(buffer: UnsafeMutablePointer<Int32>) {
}


The
int
pointer is now considered an
UnsafeMutablePointer<UInt32>
. I'm having trouble accessing the subscripts of
buffer
in Swift; i.e. I cannot call
buffer[0]
like this:

func foo(buffer: UnsafeMutablePointer<Int32>) {
myArray[0] = buffer[0] // won't compile, buffer treated as Int32
}


Out of desperation, even knowing that
UnsafeMutablePointer<Int32>
is ultimately resolved as a
Int32
type in Swift, I've tried the following:

guard let buffer = buffer.memory as? [Int] else { fatalError() }

guard let buffer = buffer as? [Int] else { fatalError() }

guard let buffer = buffer.memory as? [Int32] else { fatalError() }

guard let buffer = buffer as? [Int32] else { fatalError() }


Could someone point me to the right direction on understanding how I could access the subscript members like how the Objective-C code did?

Answer

You are overthinking it:

class MyClass {
    var myArray = [Int32](count: 4, repeatedValue: 0)

    func foo(buffer: UnsafeMutablePointer<Int32>) {
        for i in 0..<4 {
            myArray[i] = buffer[i]
        }
    }
}

You can change myArray to [Int32] to make it match buffer. Or you can cast buffer to Int:

myArray[i] = Int(buffer[i])
Comments