4

I am migrating from Swift 2 to Swift 3 and I am stuck at one point.

Swift 2

let arr = UnsafePointer<UInt32>(UnsafePointer<UInt8>(buf).advanced(by: off))
let msk = arr[0].bigEndian & 0x7fffffff

I get an error on first line saying

'init' is unavailable: use 'withMemoryRebound(to:capacity:_)' to temporarily view memory as another layout-compatible type.

I tried to use withMemoryoRebound method but I am not sure about the parameters. As per this docuentation, UnsafePointer<> has been replaced by UnsafeRawPointer. So I changed my code as below

let arr = UnsafeRawPointer(UnsafePointer<UInt8>(buf).advanced(by: off))
let msk = arr[0].bigEndian & 0x7fffffff

But here on the second line it says

Type 'UnsafeRawPointer' has no subscript members

How can I successfully convert it to Swift 3?

Prerak Sola
  • 9,517
  • 7
  • 36
  • 67
  • 1
    This might be what you are looking for: [How to get bytes out of an UnsafeMutableRawPointer?](http://stackoverflow.com/questions/38983277/how-to-get-bytes-out-of-an-unsafemutablerawpointer) – Martin R Nov 16 '16 at 17:35

2 Answers2

1

This is how you can do that operation using withMemoryRebound: Capacity in this case is 1, as you are only looking at the first element of the resulting array.

let arr = UnsafePointer<UInt8>(buf).advanced(by: off)
let msk = arr.withMemoryRebound(to: UInt32.self, capacity: 1) { p in
    return p[0].bigEndian & 0x7fffffff
}
kevin
  • 2,021
  • 21
  • 20
0

I think you are looking for something like this:

let ppp = UnsafePointer<UInt8>(buf).advanced(by: off)
let arr = unsafeBitCast(ppp, to: UnsafeMutablePointer<UInt32>.self)
Tibor Bödecs
  • 381
  • 2
  • 9