Casting between different UnsafePointer<T> in swift Casting between different UnsafePointer<T> in swift ios ios

Casting between different UnsafePointer<T> in swift


struct UnsafePointer<T> has a constructor

/// Convert from a UnsafePointer of a different type.////// This is a fundamentally unsafe conversion.init<U>(_ from: UnsafePointer<U>)

which you can use here

doThingsOnRawData(UnsafePointer<UInt8>(data.bytes))

You can even omit the generic type because it is inferred from the context:

doThingsOnRawData(UnsafePointer(data.bytes))

Update for Swift 3: As of Xcode 8 beta 6, you cannot convertdirectly between different unsafe pointers anymore.

For data: NSData, data.bytes is a UnsafeRawPointer which canbe converted to UnsafePointer<UInt8> with assumingMemoryBound:

doThingsOnRawData(data.bytes.assumingMemoryBound(to: UInt8.self))

For data: Data it is even simpler:

data.withUnsafeBytes { doThingsOnRawData($0) }