Swift
Base64
Encoding
Decoding
Programming

How can I encode/decode a string to Base64 in Swift?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Base64 is a text representation of binary data. In Swift, encoding and decoding Base64 is straightforward because String and Data work together cleanly through Foundation.

The important detail is that Base64 operates on bytes, not directly on String. That means the usual workflow is String -> Data -> Base64 String for encoding, and the reverse for decoding.

Encode a Swift String to Base64

To encode plain text, first choose an encoding such as UTF-8, convert the string into Data, and then ask that data for its Base64 representation.

swift
1import Foundation
2
3let original = "Hello, Swift"
4let data = original.data(using: .utf8)!
5let encoded = data.base64EncodedString()
6
7print(encoded)

This is the most common solution because it is short and explicit. UTF-8 is usually the correct text encoding unless you have a specific legacy requirement.

Decode a Base64 String Back into Text

Decoding goes in the other direction. First create Data from the Base64 text, then create a normal String from the decoded bytes.

swift
1import Foundation
2
3let encoded = "SGVsbG8sIFN3aWZ0"
4
5if let data = Data(base64Encoded: encoded),
6   let decoded = String(data: data, encoding: .utf8) {
7    print(decoded)
8} else {
9    print("Invalid Base64 or invalid UTF-8")
10}

The optional handling matters. A string can fail to decode for two separate reasons:

  • the Base64 input is malformed
  • the decoded bytes do not represent valid text in the encoding you requested

Build Small Helper Functions

If you need Base64 often, helper methods keep the conversion logic in one place.

swift
1import Foundation
2
3func toBase64(_ value: String) -> String? {
4    value.data(using: .utf8)?.base64EncodedString()
5}
6
7func fromBase64(_ value: String) -> String? {
8    guard let data = Data(base64Encoded: value) else {
9        return nil
10    }
11    return String(data: data, encoding: .utf8)
12}
13
14print(toBase64("apple") ?? "encode failed")
15print(fromBase64("YXBwbGU=") ?? "decode failed")

This pattern is useful when you want a clean API in view models, network code, or tests.

Encode and Decode Arbitrary Binary Data

Base64 is not only for text. If you are working with images, files, or encrypted payloads, operate directly on Data.

swift
1import Foundation
2
3let bytes = Data([0x01, 0x02, 0x03, 0xFF])
4let encoded = bytes.base64EncodedString()
5let decoded = Data(base64Encoded: encoded)
6
7print(encoded)
8print(decoded == bytes)

That matters because not all binary data should be turned into a String first. If the original input is not textual, stay with Data as long as possible.

Base64 Is Encoding, Not Protection

A common mistake is treating Base64 like encryption. It is only an encoding format. Anyone can decode it instantly.

Use Base64 when you need to transport binary data through text-only systems such as JSON, query parameters, or simple storage formats. Do not use it as a security feature for passwords, tokens, or secrets.

In iOS codebases, this often appears when you need to send an image blob, embed data in a JSON field, or store a compact textual representation in logs or fixtures. The conversion is convenient, but it should always be a deliberate transport choice rather than a default representation for all data.

Common Pitfalls

  • Forgetting to import Foundation, which provides Data and the Base64 APIs.
  • Assuming Base64 works directly on String without converting through Data.
  • Force-unwrapping decoded values when the input may be malformed.
  • Confusing Base64 encoding with encryption or hashing.
  • Using the wrong text encoding when converting decoded bytes back into a String.

Summary

  • In Swift, Base64 encoding is usually String -> Data -> base64EncodedString().
  • Decoding is Base64 String -> Data(base64Encoded:) -> String(data:encoding:).
  • Use UTF-8 unless you have a specific reason not to.
  • Prefer helper functions when the conversion appears in multiple places.
  • Treat Base64 as a transport format for bytes, not as a security mechanism.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.