如何在Swift 3中创建此函数,因为UnsafeMutablePointer现在是UnsafeMutableRawPointer

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

最佳答案

您的代码使用NSMutableData的方式不正确。您应该使用mutableBytes而不是bytes
要使用UnsafeMutableRawPointer,请检查最新的参考。
UnsafeMutableRawPointer
您可以找到storeBytes(of:toByteOffset:as:)方法。
func storeBytes(of: T, toByteOffset: Int, as: T.Type)
宣言

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

似乎第二个参数是可选的,所以您可以编写如下内容:
func writeUInt32(value:UInt32) {
    guard let data = NSMutableData(length: 4) else { return }
    data.mutableBytes.storeBytes(of: CFSwapInt32BigToHost(value), as: UInt32.self)
    writeData(data)
}

或者如果要使用新的数据类型:
func writeUInt32(value:UInt32) {
    var tempValue = CFSwapInt32BigToHost(value)
    let data = Data(bytes: &tempValue, count: MemoryLayout<UInt32>.size)
    writeData(data as NSData)
}

关于c - Swift 3中的UnsafeMutablePointer,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39691964/

10-10 04:15