UnsafePointer不再适用于swift 3

时间:2016-10-03 03:47:27

标签: ios swift swift3

我从swift 2转换为swift 3后,会弹出以下指示行的错误

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

'init'不可用:使用'withMemoryRebound(to:capacity:_)'暂时将内存视为另一种与布局兼容的类型。

在swift2中

就像

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

有人可以解释一下吗? 对不起,我对swift3很新。

我对

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

但仍然应该在变量中输入什么值?对不起,我有搜索但很糟糕,我找不到解决方案

2 个答案:

答案 0 :(得分:7)

你可以试试这个:

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

原始指针是用于访问非类型数据的指针。

assumingMemoryBound(to:)可以从UnsafeRawPointer转换为UnsafePointer<T>

参考:Swift 3.0 Unsafe World

答案 1 :(得分:0)

如果arrayArray,您最好的选择是使用withUnsafeBufferPointer

array.withUnsafeBufferPointer { buffer in
    // do something with 'buffer'
    // (if you need an UnsafePointer rather than an UnsafeBufferPointer,
    // you can access that via the buffer's .baseAddress property)
}

确保你不让缓冲区指针从闭包中逃脱,因为它在它之外是无效的。