在Swift 4中将数据转换为DispatchData [英] Convert Data to DispatchData in Swift 4

查看:121
本文介绍了在Swift 4中将数据转换为DispatchData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将项目迁移到Swift 4,但无法弄清楚应该如何在Swift 4中使用新的API:s.以下代码是旧的Swift 3方式(从函数中间开始)因此是后卫):

I am migrating a project to Swift 4 and I cannot figure out how I am supposed to use the new API:s to do this in Swift 4. The following code is the old Swift 3 way (from the middle of a function hence the 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

Now it gives the following warning: init(bytes:)' is deprecated: Use init(bytes: UnsafeRawBufferPointer) instead

为此,您需要访问类型为UnsafeRawBufferPointer而不是UnsafeBufferPointer<UInt8>

In order to do that you need to get access to a variable with the type UnsafeRawBufferPointer instead of UnsafeBufferPointer<UInt8>

推荐答案

使用withUnsafeBytes获取数据字节的UnsafeRawPointer, 根据该指针和计数创建一个UnsafeRawBufferPointer, 并将其传递给DispatchData构造函数:

Use withUnsafeBytes to get an UnsafeRawPointer to the data bytes, create an UnsafeRawBufferPointer from that pointer and the count, and pass it to the DispatchData constructor:

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"视图创建一个数组,然后 使用withUnsafeBytes获取UnsafeRawBufferPointer 表示数组的连续元素存储:

Alternatively, create an array from the Strings UTF-8 view and use withUnsafeBytes to get an UnsafeRawBufferPointer representing the arrays contiguous element storage:

let formattedString = "A string"
let data = Array(formattedString.utf8).withUnsafeBytes {
    DispatchData(bytes: $0)
}

这篇关于在Swift 4中将数据转换为DispatchData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆