Prerak Sola
Prerak Sola

Reputation: 10019

Swift 3 Unsafe Pointer

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?

Upvotes: 4

Views: 1080

Answers (2)

kevin
kevin

Reputation: 2071

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
}

Upvotes: 1

Tibor B&#246;decs
Tibor B&#246;decs

Reputation: 381

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)

Upvotes: 0

Related Questions