Blog

Base64 encode and decode strings

Jun 4, 2020 swiftextensions

In this post, we’ll discuss how to Base64 encode and decode strings in Swift. We’ll also create a couple of extensions to make this easier to use and more readable.

The basics

Base64-encoding strings in Swift is very easy. You just have to convert the string to data, then encode that data with base64EncodedString():

let string = "Let's encode this string"
let encoded = string.data(using: .utf8)?.base64EncodedString()

To decode a Base64 encoded string, you just have to convert it to data, then create a string from the decoded data:

guard let data = Data(base64Encoded: self) else { return nil }
return String(data: data, encoding: .utf8)

Note that both encoding and decoding can fail, which means that they return optional strings.

Extending String

Although the above operations are very easy and straightforward, I prefer to use more convenient and readable extensions, to avoid having to write the same code over and over.

To Base64 encode and devode strings, I just wrap the logic in a String extension:

extension String {

    func base64Encoded() -> String? {
        data(using: .utf8)?.base64EncodedString()
    }

    func base64Decoded() -> String? {
        guard let data = Data(base64Encoded: self) else { return nil }
        return String(data: data, encoding: .utf8)
    }
}

We can now encode and decode strings like this:

let string = "Let's encode this string"
let encoded = string.base64Encoded()
let decoded = encoded?.base64Decoded()

I think that this is a lot cleaner. Since the decode logic requires a guard, you also save one line each time and avoid having to use control flow where you may not want it.

Source code

I have added these extensions to my SwiftKit library. You can find the source code here. Feel free to try it out and let me know what you think!