Lucas Farah Lucas Farah - 2 months ago 30
C Question

UnsafeMutablePointer in Swift 3

I how can I create this function in Swift 3, since

UnsafeMutablePointer
is now
UnsafeMutableRawPointer
?

func writeUInt32(value:UInt32) {
guard let data = NSMutableData(length: 4) else { return }
UnsafeMutablePointer<UInt32>(data.bytes).memory = CFSwapInt32BigToHost(UInt32(value))
writeData(data)
}

Answer

Your code is using NSMutableData in a bad manner. You should use mutableBytes rather than bytes.

To work with UnsafeMutableRawPointer, check the latest reference.

UnsafeMutableRawPointer

You can find storeBytes(of:toByteOffset:as:) method.

func storeBytes(of: T, toByteOffset: Int, as: T.Type)

Declaration

func storeBytes<T>(of value: T, toByteOffset offset: Int = default, as: T.Type)

Seems the second parameter is optional, so you can write something like this:

func writeUInt32(value:UInt32) {
    guard let data = NSMutableData(length: 4) else { return }
    data.mutableBytes.storeBytes(of: CFSwapInt32BigToHost(value), as: UInt32.self)
    writeData(data)
}

Or if you want to work with new data type Data:

func writeUInt32(value:UInt32) {
    var tempValue = CFSwapInt32BigToHost(value)
    let data = Data(bytes: &tempValue, count: MemoryLayout<UInt32>.size)
    writeData(data as NSData)
}
Comments