Navi Navi - 1 month ago 6
Swift Question

swift 2 to 3 conversion UnsafePointer<UInt8>

I need to call the following API in a objective-c header in J2Objc.

/**
* Create a new array of a specified length, setting the elements to the values in buf.
*/
class IOSByteArray: NSObject {
...
+ (instancetype)newArrayWithBytes:(const jbyte *)buf count:(NSUInteger)count;
...
}


In swift 2, I could do the following:

func myFunc() -> IOSByteArray {
return IOSByteArray.newArray(withBytes: UnsafePointer<UInt8>(data.bytes), count: UInt(data.count))
}


In swift 3, I get the error:

"Cannot invoke initializer for type 'UnsafePointer<UInt8>' with an argument list of type '(Array<UInt8>)'"


I cannot figure out how to make the equivalent call in swift 3.

I get that https://swift.org/migration-guide/se-0107-migrate.html#automatic-migration-cases provides an explanation of the why and the how. But its a little too erudite for me.

Help!

Answer

In Swift 3 you should use Data class instead of NSData

With Data class you can use withUnsafeBytes to get convert the bytes to UnsafePointer and do it like this

func myFunc() -> IOSByteArray {
    return data.withUnsafeBytes({ (unsafeBytes: UnsafePointer<UInt8>) -> IOSByteArray in
        return IOSByteArray.newArray(withBytes: unsafeBytes, count: UInt(data.count))
    }
}
Comments