How to convert String to byte in Swift?
Like String .getBytes()
in Java.
-
possible duplicate of [How to convert NSString to bytes](http://stackoverflow.com/questions/881482/how-to-convert-nsstring-to-bytes) – ahruss Jul 30 '14 at 02:31
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)

- 1,756
- 2
- 27
- 43

- 2,082
- 2
- 17
- 14
-
-
-
5Apparently not working in Swift 4. Use `var buf : [UInt8] = Array(str.utf8)` instead. – PJ_Finnegan Oct 16 '17 at 13:13
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)

- 63,902
- 28
- 145
- 142
edit/update: Xcode 11.5 • Swift 5.2
extension StringProtocol {
var data: Data { .init(utf8) }
var bytes: [UInt8] { .init(utf8) }
}
"12345678".bytes // [49, 50, 51, 52, 53, 54, 55, 56]

- 229,809
- 59
- 489
- 571
String.withCString is the peer to Java's String.getBytes(void). Use it like this (extra typing added):
let s = "42"
s.withCString {
( bytes : (UnsafePointer<CChar>) ) -> Void in
let k = atoi(bytes)
println("k is \(k)")
}

- 13,957
- 6
- 30
- 40
Another option, for when you need to be able to pass to C-library functions:
let str = hexColour.cStringUsingEncoding(NSUTF8StringEncoding)
let x = strtol(str!, nil, 16)

- 39,719
- 45
- 189
- 235
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.

- 4,289
- 3
- 43
- 70
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

- 3,479
- 1
- 31
- 41