Search code examples
iosswiftswift3

UnsafePointer no longer works in swift 3


After I convert from swift 2 to swift 3, there is an error pop up for the below metioned line

let value = UnsafePointer<UInt32>(array1).pointee

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

in swift2 it is like

let value = UnsafePointer<UInt32>(array1).memory

Can someone explain please? Sorry I'm quite new to swift3

After i have make the changes to

let abc = UnsafePointer<UInt32>(array1).withMemoryRebound(to: <#T##T.Type#>, capacity: <#T##Int#>, <#T##body: (UnsafeMutablePointer<T>) throws -> Result##(UnsafeMutablePointer<T>) throws -> Result#>)

but still what value should go in to the variable? Sorry, i have search around but too bad i can't find a solution


Solution

  • You can try this:

    let rawPointer = UnsafeRawPointer(array1)
    let pointer = rawPointer.assumingMemoryBound(to: UInt32.self)
    let value = pointer.pointee
    

    Raw pointer is a pointer for accessing untype data.

    assumingMemoryBound(to:) can convert from an UnsafeRawPointer to UnsafePointer<T>.

    Reference :Swift 3.0 Unsafe World