How to convert String to byte in Swift?

YuXuan Fu picture YuXuan Fu · Jul 30, 2014 · Viewed 41.7k times · Source

How to convert String to byte in Swift? Like String .getBytes()in Java.

Answer

Albin Stigo picture Albin Stigo · Sep 19, 2014

There is a more elegant way.

Swift 3:

let str = "Hello"
let buf = [UInt8](str.utf8)

Swift 4: (thanks to @PJ_Finnegan)

let str = "Hello"
let buf: [UInt8] = Array(str.utf8)