Usage of withMemoryRebound with Apples Swift 3 beta 6

假装没事ソ 提交于 2019-12-01 03:55:09

Pointer conversions are much more "verbose" now since Xcode 8 beta 6. Here is a possible solution:

func binarytotype <T> (_ value: [UInt8], _: T.Type) -> T {
    return value.withUnsafeBufferPointer {
        UnsafeRawPointer($0.baseAddress!).load(as: T.self)
    }
}

func typetobinary<T>(_ value: T) -> [UInt8] {
    var data = [UInt8](repeating: 0, count: MemoryLayout<T>.size)
    data.withUnsafeMutableBufferPointer {
        UnsafeMutableRawPointer($0.baseAddress!).storeBytes(of: value, as: T.self)
    }
    return data
}

Example:

let d = typetobinary(UInt16(1000))
print(d) // [232, 3]
let i = binarytotype(d, UInt16.self)
print(i) // 1000

See SE-0107 UnsafeRawPointer API for detailed information about the new raw pointer API.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!