Base64 Encoding in Swift
Our first program will demonstrate base64 encoding and decoding. Here’s the full source code:
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:
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.