How to convert String to byte in Swift?
Like String .getBytes()in Java.
7 Answers
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)
3 Comments
var buf, might as well be let bufvar buf : [UInt8] = Array(str.utf8) instead.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)
3 Comments
string.utf8 or string.utf16 should do something like what you are asking for. See here for more info: https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html.
Comments
Swift 4.1.
It depends what you want to achieve. For the same question, I used...
let message = "Happy"
for v in message.utf8 {
print(v)
}
I then performed the operations I needed on the individual byte. The output is:
//72
//97
//112
//112
//121
https://developer.apple.com/documentation/swift/string.utf8view