[英]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在我从 swift 2 转换为 swift 3 后,下面提到的行会弹出一个错误
let value = UnsafePointer<UInt32>(array1).pointee
'init' is unavailable: use 'withMemoryRebound(to:capacity:_)' to temporarily view memory as another layout-compatible type. 'init' 不可用:使用 'withMemoryRebound(to:capacity:_)' 暂时将内存视为另一种布局兼容类型。
in swift2 it is like在swift2中它就像
let value = UnsafePointer<UInt32>(array1).memory
Can someone explain please?有人可以解释一下吗? Sorry I'm quite new to swift3抱歉,我对 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抱歉,我四处搜索,但太糟糕了,我找不到解决方案
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>
. assumingMemoryBound(to:)
可以从UnsafeRawPointer
转换为UnsafePointer<T>
。
Reference : Swift 3.0 Unsafe World参考: Swift 3.0 不安全的世界
If array
is an Array
, your best bet is to use withUnsafeBufferPointer
:如果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)
}
Make sure you don't let the buffer pointer escape from the closure, because it will not be valid outside it.确保不要让缓冲区指针从闭包中逸出,因为它在闭包之外无效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.