0

For iPhone5 (10.2) simulator this function:

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

crashes at $0.baseAddress!.load(as: T.self) with this error:

fatal error: load from misaligned raw pointer

Does somebody know the solution?

I'm using this code:

https://stackoverflow.com/a/26954091/1979882

EDIT it works for iPhone5s but not iPhone5

Community
  • 1
  • 1
Vyacheslav
  • 26,359
  • 19
  • 112
  • 194

1 Answers1

6

Indeed, it crashes as you described. The solution is to use this function to convert byte array to desired type:

func fromByteArray<T>(_ value: [UInt8], _: T.Type) -> T {
        return value.withUnsafeBufferPointer {
            $0.baseAddress!.withMemoryRebound(to: T.self, capacity: 1) {
                $0.pointee
            }
        }
    }

Here is my results from testing (red crashes the iPhone 5 simulator for unknown reason): enter image description here

Artur Kucaj
  • 1,071
  • 1
  • 11
  • 16