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.
我知道有很多关于NSData的前Swift3问题。我很好奇,如何将Swift3字符串转换为utf8编码(带有或没有空终止),以Swift3数据对象。
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.
必须做中间数组()构造似乎是错误的。
2 个解决方案
#1
55
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:)
如果您想终止带有null的数据,只需将一个0附加到它。或者您可以调用cString(使用:)
let cString = input.cString(using: .utf8)! // null-terminated
#2
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.
NSString方法从NSFoundation框架应该被放弃,以支持Swift标准库。数据可以用任何元素都是UInt8的序列初始化。字符串。UTF8View满足这个要求。
let input = "Hello World"
let data = Data(input.utf8)
// [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
There is no such thing as null terminated data representation of a string. String null termination is an implementation detail of C language and it should not leak outside.
没有一个字符串的空终止数据表示。字符串null终止是C语言的一个实现细节,它不应该在外部泄漏。
If you are planning to work with C APIs, please take a look the following property of String
type:
如果您打算使用C api,请查看以下字符串类型的属性:
public var utf8CString: ContiguousArray<CChar> { get }
#1
55
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:)
如果您想终止带有null的数据,只需将一个0附加到它。或者您可以调用cString(使用:)
let cString = input.cString(using: .utf8)! // null-terminated
#2
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.
NSString方法从NSFoundation框架应该被放弃,以支持Swift标准库。数据可以用任何元素都是UInt8的序列初始化。字符串。UTF8View满足这个要求。
let input = "Hello World"
let data = Data(input.utf8)
// [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
There is no such thing as null terminated data representation of a string. String null termination is an implementation detail of C language and it should not leak outside.
没有一个字符串的空终止数据表示。字符串null终止是C语言的一个实现细节,它不应该在外部泄漏。
If you are planning to work with C APIs, please take a look the following property of String
type:
如果您打算使用C api,请查看以下字符串类型的属性:
public var utf8CString: ContiguousArray<CChar> { get }