Swift 3 method to create utf8 encoded Data from String

随声附和 提交于 2020-01-10 08:41:04

问题


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.

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.


回答1:


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:)

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



回答2:


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.

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:

public var utf8CString: ContiguousArray<CChar> { get }

Data can be obtained after CChar is converted to UInt8:

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


来源:https://stackoverflow.com/questions/37889698/swift-3-method-to-create-utf8-encoded-data-from-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!