1

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)
}

1 Answer 1

1

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)
}
Sign up to request clarification or add additional context in comments.

2 Comments

Strictly speaking, it should be CFSwapInt32HostToBig(value), or just value.bigEndian :)
@MartinR, thanks. In fact, I am always confused with them including htonl and ntohl...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.