0

I use a method within my code to convert raw bytes to Ints. The code I used previously was:

func convert(from data: Data) -> Int? {
  return data.withUnsafeBytes { $0.pointee }
}

This used to work correctly, until XCode 8.3 with Swift 3.1 support came along. Now the same method works correctly on iOS 10 devices, but fails (returns absurdly large numbers) on devices (and simulators) running iOS 9.3.

Example code: Data(bytes: [0]).withUnsafeBytes { $0.pointee } as Int returns -4611686018427387903

Anyone experiencing the same issue?

axelcdv
  • 753
  • 6
  • 18
  • 1
    I don't see `withUnsafePointer` (from your title) in your code. – matt Mar 29 '17 at 16:53
  • What is this code supposed to do? `withUnsafeBytes` is unsafe. The whole point is that you _cannot_ use `$0.pointee` outside the curly braces, let alone _return_ it the way you are doing. This seems like an x-y problem: you should explain what you want to do, not insist on the (possibly wrong) way you are already doing it. Besides, a Data _is_ already a collection of Int — actually, of UInt8 — so it's hard to see what the problem is to begin with; there is nothing to do. – matt Mar 29 '17 at 16:54
  • If the point is that the bytes are to be _assembled_ into a single Int, you might want to look at this: http://stackoverflow.com/questions/32769929/convert-bytes-uint8-array-to-int-in-swift (I would suggest that in that case your question is a duplicate and should just be deleted). – matt Mar 29 '17 at 16:58
  • 1. Indeed, fixed the title to the correct method 2. It is indeed supposed to build the data into an int 3. The issue is that this used to work on iOS 9.3 with Swift 3.0, but no longer (same for the solution you referred to) – axelcdv Mar 29 '17 at 17:02
  • Okay! Well, that's why I didn't actually mark this as a duplicate. :) – matt Mar 29 '17 at 17:07
  • 2
    `Data(bytes: [0]).withUnsafeBytes { $0.pointee } as Int` causes *undefined behaviour.* You are reading 4 or 8 bytes from an array with only one byte. That might give the correct result by pure chance if there are zeros in the memory following the element storage. – Martin R Mar 29 '17 at 17:42

0 Answers0