UnsafePointer 不再适用于 swift 3
Posted
技术标签:
【中文标题】UnsafePointer 不再适用于 swift 3【英文标题】:UnsafePointer no longer works in swift 3 【发布时间】:2016-10-03 03:47:26 【问题描述】:我从 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#>)
但仍然应该将什么值放入变量中?对不起,我已经搜索了但是太糟糕了我找不到解决方案
【问题讨论】:
Results from C functions that return nullable pointers must be explicitly unwrapped before accessing the pointee property (formerly memory) or subscript elements. Optional chaining syntax works well here, e.g. result?.pointee = sum.
可能会有所帮助...swift.org/migration-guide
请展示你真正想要做什么。
array1
是什么类型的?UnsafeRawPointer
?
@LinShiwei var array1 = [UInt8](count4: 重复 0)
【参考方案1】:
你可以试试这个:
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
【讨论】:
【参考方案2】:如果array
是Array
,最好使用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)
确保不要让缓冲区指针从闭包中逃逸,因为它在闭包之外无效。
【讨论】:
以上是关于UnsafePointer 不再适用于 swift 3的主要内容,如果未能解决你的问题,请参考以下文章
无法为类型 Unsafepointer Swift 3.0 转换初始化变量
geocoder.geocodeAddressString 今天不再适用于快速更新
Swift 到 C 的桥接:字符串到 UnsafePointer<Int8>?是否自动桥接?
Swift 桥接二维数组以键入 UnsafePointer<UnsafeMutablePointer<Double>?>?