26

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
  • Would you agree that this question should be reviewed again as accepted answer uses NSFoundation API instead of Swift one? Commented Aug 25, 2018 at 9:51

2 Answers 2

61

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
Sign up to request clarification or add additional context in comments.

2 Comments

That's perfect, thanks. Amusingly, the cString method returns a [UInt8]
If this answered your question satisfactorily, please mark it as the correct answer. This encourages more in the community to answer your questions and ensures that when other users stumble onto this page with the same question, they can easily find the correct answer.
4

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]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.