Java String.getBytes() equivalent in swift

Is there any way to convert string into bytes in swift.
currently i try to convert String into Data type and then try to get bytes from it .but the result is not the same with java String.getBytes() does. Any Help .
Thank you . I'm just beginner on study swift.

import Foundation

"myString".data(using: .utf8)!

I think the default getBytes in Java's return encoding is dependent on the system's default, and I'm not sure how to detect that, but there's probably some Darwin and Linux way of doing it.

hi sir "myString".data(using: .utf8)! just only return total byte of a string like 8 bytes.

If you want an array of bytes, you can just do:

import Foundation

let bytes = Array("myString".data(using: .utf8)!)

That is a different problem. The description of a Data value only produces a string like "NNN bytes". You can use

let data = "Hello world".data(using: .utf8)!
print(data as NSData) // <48656c6c 6f20776f 726c64>

to see the contents as a hex string. (I suggested to add some hex dump method to Data some time ago: [SR-2514] Add a "hex dump" method to `Data` · Issue #4115 · apple/swift-corelibs-foundation · GitHub).

Independent of that, Data is a collection of UInt8 (bytes), and you can access its contents via subscripting.

Edit: Apparently, the above workaround does not work anymore with Swift 4.2 (Xcode 10):

let data = "Hello world".data(using: .utf8)!
print(data as NSData) // _NSInlineData

I wonder if that is an intentional change.

Or (to avoid the scary forced unwrapping):

Data("myString".utf8)
4 Likes

If you just want an array then you can skip importing Foundation and simply write:
let bytes = Array("mystring".utf8)

2 Likes