Swift: Bytes for Beginners (Part II)


Last time a string was converted into bytes and then transformed from bytes back into a string. Following on from this, I'm going to start by creating two separate byte arrays:
let strA = "Hello, "
var buffA = [UInt8](strA.utf8)

let strB = "playground"
var buffB = [UInt8](strB.utf8)
Note: I've simplified the construction of the byte arrays (aka buffers) since the last post and created them all on one line. This is thanks to reading this StackOverflow post.

Joining byte arrays together

Now I'm simply going to join the two byte arrays together.
buffA += buffB

And the same as last time transform this back into a string.
if let a = String.stringWithBytes(buffA, encoding: NSUTF8StringEncoding) {
    a // returns "Hello, playground"
}

Reversing a byte array

As you can see the byte array is being treated like any other array. Now let's take this a step further and use one of Swift's algorithms to manipulate the array:
buffA = reverse(buffA)
if let a = String.stringWithBytes(buffA, encoding: NSUTF8StringEncoding) {
    a // returns "dnuorgyalp ,olleH"
}
Finally, let's end with the entire code for copying and pasting into a playground.
let strA = "Hello, "
var buffA = [UInt8](strA.utf8)

let strB = "playground"
var buffB = [UInt8](strB.utf8)

buffA += buffB
buffA = reverse(buffA)

if let a = String.stringWithBytes(buffA, encoding: NSUTF8StringEncoding) {
    a // returns "dnuorgyalp ,olleH"

}
Try for yourself some other ways of manipulating the byte array before transforming it back into a string; get used to the idea of being able to play with the array and the ways in which you can change it without breaking it.
Endorse on Coderwall

Comments