Base64 encode and decode strings
- Jun 4, 2020
- #swift
In this post, we’ll discuss how to Base64 encode and decode strings in Swift. We’ll then create extensions that make this a lot easier and more readable.
The basics
It’s very easy to Base64 encode strings in Swift. You just have to convert it 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 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 the operations produce optional strings.
Extending String
Although the above operations are very easy and straightforward, I prefer to use more convenient extensions, to avoid having to write the same code over and over.
To encode strings, I just wrap the encoding logic in a String
extension:
func base64Encoded() -> String? {
data(using: .utf8)?.base64EncodedString()
}
I also do the same for the decoding logic:
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 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 and the unit tests here.