j.s.com j.s.com - 1 year ago 173
Swift Question

Usage of withMemoryRebound with Apples Swift 3 beta 6

I have the following Problem. I want to convert my old function (worked until Swift 3 beta 5):

func binarytotype <T> (_ value: [UInt8], _: T.Type) -> T
return value.withUnsafeBufferPointer
return UnsafePointer<T>($0.baseAddress!).pointee

To Swift 3 beta 6 Syntax. This function converts an array of UInt8 to another type, for example:

let b: [UInt8] = [1,2,3,4,5,6,7,8]
var number: Double = binarytotype(b, Double.self)

But for now this does not work any more in beta 6 and I have to use withMemoryRebound but I really do not know, how to make it run. Can anybody help me?

The reverse function of this was:

func typetobinary <T> (_ value: T) -> [UInt8]
var v: T = value
return withUnsafePointer(to: &v)
Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>($0), count: MemoryLayout<T>.size))

This does not work any more, too. Same problem. Both are needed for some of my projects. This reverse function was called as:

var binary: [UInt8] = typetobinary(number)

Answer Source

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


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.