string 从字符串创建 utf8 编码数据的 Swift 3 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37889698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:32:54  来源:igfitidea点击:

Swift 3 method to create utf8 encoded Data from String

stringutf-8swift3

提问by Travis Griggs

I know there's a bunch of pre Swift3 questions regarding NSData stuff. I'm curious how to go between a Swift3 Stringto a utf8 encoded (with or without null termination) to Swift3 Dataobject.

我知道在 Swift3 之前有很多关于 NSData 的问题。我很好奇如何在 Swift3String到 utf8 编码(有或没有空终止)到 Swift3Data对象之间进行转换。

The best I've come up with so far is:

到目前为止我想出的最好的是:

let input = "Hello World"
let terminatedData = Data(bytes: Array(input.nulTerminatedUTF8))
let unterminatedData = Data(bytes: Array(input.utf8))

Having to do the intermediate Array()construction seems wrong.

必须进行中间Array()构造似乎是错误的。

回答by Code Different

It's simple:

这很简单:

let input = "Hello World"
let data = input.data(using: .utf8)!

If you want to terminate datawith null, simply appenda 0 to it. Or you may call cString(using:)

如果您想以datanull终止,只需append给它一个 0。或者你可以打电话cString(using:)

let cString = input.cString(using: .utf8)! // null-terminated

回答by Wojciech Nagrodzki

NSStringmethods from NSFoundationframework should be dropped in favor for Swift Standard Library equivalents. Data can be initialized with any Sequencewhich elements are UInt8. String.UTF8Viewsatisfies this requirement.

NSStringNSFoundation应该放弃框架中的方法,转而使用 Swift 标准库等价物。可以使用任何Sequence元素来初始化数据UInt8String.UTF8View满足这个要求。

let input = "Hello World"
let data = Data(input.utf8)
// [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]

String null termination is an implementation detail of C language and it should not leak outside. If you are planning to work with C APIs, please take a look at the utf8CStringproperty of Stringtype:

String null 终止是 C 语言的一个实现细节,不应泄漏到外部。如果您打算使用 C API,请查看typeutf8CString属性String

public var utf8CString: ContiguousArray<CChar> { get }

Datacan be obtained after CCharis converted to UInt8:

Data后就可以得到CChar转换为UInt8

let input = "Hello World"
let data = Data(input.utf8CString.map { UInt8(##代码##) })
// [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 0]