Search code examples
swiftnsdataswift3

Convert NSData UnsafePointer operation to Swift 3


I am having a heck of a time converting my working NSData swift 2.2 code into 3.

I have a lot of errors that are all similar in one file, and I can't get it to compile to check my conversion. Here are the original lines:

let dataPtr = UnsafePointer<UInt8>(bytes).advancedBy(f_offset)

let retVal = UnsafePointer<T>(dataPtr).memory

I think the first line gets converted to this:

let dataPtr = UnsafeRawPointer(bytes).advanced(by: f_offset)

I can't figure out how to convert the second line, because memory is not a member of UnsafeRawPointer, which Swift 3 seems to require.

How can I convert those two lines?

If I get more specific errors, I will post them.


Solution

  • Assuming your bytes is taken from some NSData's bytes property:

    let bytes = nsData.bytes
    

    Then you have no need to use UnsafeRawPointer(_:):

    let dataPtr = bytes.advanced(by: f_offset)
    

    And may use a method of UnsafeRawPointer:

    let retVal = dataPtr.load(as: T.self)