0

I have this code right here that worked in preexisting swift.

func toByteArray<T>(_ value: T) -> [UInt8] {
    var val = value
    //let sock = socket(PF_INET, SOCK_STREAM, 0) // added in 11/16
    return withUnsafePointer(to: &val) {
        Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>($0), count: MemoryLayout<T>.size))
    }
}

This does not work, as it prints an error message that says init is unavailable. Use withMemoryRebound(to:capacity:_). Ok, so I have researched through google and found some options that should work, where now my updated code is

 func toByteArray<T>(_ value: T) -> [UInt8] {
    var val = value
    return withUnsafePointer(to: &val) {
        //another swift 3 change with UnsafePointer<UInt8>
        Array(UnsafeBufferPointer(start: ($0).withMemoryRebound(to:UInt8.self, capacity: 1){ SCNetworkReachabilityCreateWithAddress(nil, $0)}, count: MemoryLayout<T>.size))
    }

}

Which should work, however it says use of unresolved identifier SCNetworkReachabilityCreateWithAddress, which I don't understand and can't find a solution for it. Any thoughts on what the issue is? I feel it is something that is with the updated Swift and Xcode.

timedwalnut
  • 94
  • 1
  • 13

2 Answers2

2

I wonder if making an Array of UInt8 would be the best solution for your actual purpose.

For example, Data works as a Collection of UInt8 in Swift 3.

func toData<T>(_ value: T) -> Data {
    var val = value
    return Data(bytes: &val, count: MemoryLayout<T>.size)
}
for byte in toData(i) {
    print(String(format: "%02X", byte))
}
/* output:
 78
 56
 34
 12
 00
 00
 00
 00
 */

But if you insist on using Array, you can write something like this using UnsafeRawBufferPointer (available since Swift 3.0.1/Xcode 8.1):

func toByteArray<T>(_ value: T) -> [UInt8] {
    var val = value
    return Array(UnsafeRawBufferPointer(start: &val, count: MemoryLayout<T>.size))
}
OOPer
  • 47,149
  • 6
  • 107
  • 142
  • Tried it with array, however it still says use of unresolved identifier. I am sure there are some simple solutions to that statement? I don't know why I would get that. – timedwalnut Nov 15 '16 at 19:52
  • _it still says use of unresolved identifier_ To what identifier? And please show your Xcode version with build number. My code is actually tested on Xcode 8.1 (8B62). – OOPer Nov 15 '16 at 22:40
0

Try this:

func toByteArray<T>(_ value: T) -> Any {
    var value = value

    let pointerToT = withUnsafePointer(to: &value) { UnsafeRawPointer($0) }
    let sizeOfT = MemoryLayout<T>.size

    let pointerToBytes = pointerToT.bindMemory(to: UInt8.self, capacity: sizeOfT)
    let bytes = Array(UnsafeBufferPointer(start: bytePointer, count: sizeOfT))

    return bytes
}
Alexander
  • 59,041
  • 12
  • 98
  • 151