Base64 Encoding in Swift
Our first program will demonstrate base64 encoding and decoding. Here’s the full source code:
import Foundation
func main() {
// Here's the string we'll encode/decode
let data = "abc123!?$*&()'-=@~"
// Swift provides built-in support for base64 encoding/decoding
// Here's how to encode using the standard encoder
if let encodedData = data.data(using: .utf8) {
let sEnc = encodedData.base64EncodedString()
print(sEnc)
// Decoding may return nil, which you can check
// if you don't already know the input to be well-formed
if let decodedData = Data(base64Encoded: sEnc),
let sDec = String(data: decodedData, encoding: .utf8) {
print(sDec)
}
}
print()
// This encodes/decodes using a URL-safe base64 format
if let encodedData = data.data(using: .utf8) {
let uEnc = encodedData.base64EncodedString(options: .urlSafeAlphabet)
print(uEnc)
if let decodedData = Data(base64Encoded: uEnc),
let uDec = String(data: decodedData, encoding: .utf8) {
print(uDec)
}
}
}
main()
Swift provides built-in support for base64 encoding/decoding through the Foundation
framework.
We start by importing the Foundation
framework, which provides the necessary functionality for base64 encoding and decoding.
In the main()
function, we define a string data
that we’ll use for encoding and decoding.
For standard base64 encoding, we first convert the string to Data
using UTF-8 encoding. Then we use the base64EncodedString()
method to encode it. For decoding, we use Data(base64Encoded:)
to convert the base64 string back to Data
, and then create a new String
from that data.
For URL-safe base64 encoding, we use the same base64EncodedString()
method, but with the .urlSafeAlphabet
option. This replaces the standard ‘+’ and ‘/’ characters with ‘-’ and ‘_’ respectively, making the output safe for use in URLs.
Note that in Swift, these operations can fail (for example, if the string can’t be encoded as UTF-8), so we use optional binding (if let
) to safely unwrap the results.
To run the program, save it as base64_encoding.swift
and use the Swift compiler:
$ swift base64_encoding.swift
YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~
YWJjMTIzIT8kKiYoKSctPUB-
abc123!?$*&()'-=@~
The string encodes to slightly different values with the standard and URL-safe base64 encoders (trailing +
vs -
) but they both decode to the original string as desired.