Swift 3 method to create utf8 encoded Data from String

Swift 3 method to create utf8 encoded Data from String



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.


String


Data



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





Would you agree that this question should be reviewed again as accepted answer uses NSFoundation API instead of Swift one?
– Wojciech Nagrodzki
Aug 25 at 9:51




2 Answers
2



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


append


cString(using:)


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





That's perfect, thanks. Amusingly, the cString method returns a [UInt8]
– Travis Griggs
Jun 17 '16 at 23:03


cString


[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.
– Matthew Seaman
Jun 20 '16 at 2:19




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


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:


utf8CString


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($0) )
// [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 0]






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế