我正在将一个项目迁移到 Swift 4,但我不知道如何使用新的 API:s 在 Swift 4 中执行此操作。以下代码是旧的 Swift 3 方式(来自函数的中间)因此是 guard ):
let formattedString = "A string"
guard let stringData: Data = formattedString.data(using: .utf8) else { return }
let data: DispatchData = [UInt8](stringData).withUnsafeBufferPointer { (bufferPointer) in
return DispatchData(bytes: bufferPointer)
}
现在它给出以下警告:init(bytes:)' is deprecated: Use init(bytes: UnsafeRawBufferPointer) instead
为了做到这一点,您需要访问类型为 UnsafeRawBufferPointer
的变量。而不是UnsafeBufferPointer<UInt8>
最佳答案
使用withUnsafeBytes
获取数据字节的UnsafeRawPointer
,
根据该指针和计数创建一个 UnsafeRawBufferPointer
,
并将其传递给 DispatchData
构造函数:
let formattedString = "A string"
let stringData = formattedString.data(using: .utf8)! // Cannot fail!
let data = stringData.withUnsafeBytes {
DispatchData(bytes: UnsafeRawBufferPointer(start: $0, count: stringData.count))
}
或者,从字符串 UTF-8 View 创建一个数组,然后
使用 withUnsafeBytes
获取 UnsafeRawBufferPointer
表示数组连续元素存储:
let formattedString = "A string"
let data = Array(formattedString.utf8).withUnsafeBytes {
DispatchData(bytes: $0)
}
关于swift - 在 Swift 4 中将数据转换为 DispatchData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46346598/