Reputation: 22252
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.
Upvotes: 26
Views: 40206
Reputation: 2868
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]
Upvotes: 4
Reputation: 93141
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
Upvotes: 61