How to convert String to byte in Swift?
How to convert String to byte in Swift?
Like String .getBytes()
in Java.
Solution 1:
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)
Solution 2:
You can iterate through the UTF8 code points and create an array:
var str = "hello, world"
var byteArray = [Byte]()
for char in str.utf8{
byteArray += [char]
}
println(byteArray)