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
Swift 3 method to create utf8 encoded Data from String
提问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 String
to a utf8 encoded (with or without null termination) to Swift3 Data
object.
我知道在 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 data
with null, simply append
a 0 to it. Or you may call cString(using:)
如果您想以data
null终止,只需append
给它一个 0。或者你可以打电话cString(using:)
let cString = input.cString(using: .utf8)! // null-terminated
回答by Wojciech Nagrodzki
NSString
methods from NSFoundation
framework should be dropped in favor for Swift Standard Library equivalents. Data can be initialized with any Sequence
which elements are UInt8
. String.UTF8View
satisfies this requirement.
NSString
NSFoundation
应该放弃框架中的方法,转而使用 Swift 标准库等价物。可以使用任何Sequence
元素来初始化数据UInt8
。String.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 utf8CString
property of String
type:
String null 终止是 C 语言的一个实现细节,不应泄漏到外部。如果您打算使用 C API,请查看typeutf8CString
属性String
:
public var utf8CString: ContiguousArray<CChar> { get }
Data
can be obtained after CChar
is 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]