Base64 in Swift
How to encode and decode Base64 in Swift — with copy-paste examples and a live converter to check your output.
Swift's Foundation Data type has built-in Base64 support: base64EncodedString() to encode and Data(base64Encoded:) to decode.
Encode to Base64 in Swift
import Foundation
let encoded = Data("Hello, World!".utf8).base64EncodedString()Decode Base64 in Swift
import Foundation
if let data = Data(base64Encoded: encoded) {
let text = String(data: data, encoding: .utf8)
}Notes & gotchas
Data(base64Encoded:) returns an optional and fails (returns nil) on invalid input rather than throwing. Foundation has no built-in URL-safe variant — swap "+/" for "-_" and re-pad manually if you need one.
Try it live
Base64 in Swift — FAQ
How do I Base64 encode a string in Swift?+
Use the code shown above. Data(base64Encoded:) returns an optional and fails (returns nil) on invalid input rather than throwing. Foundation has no built-in URL-safe variant — swap "+/" for "-_" and re-pad manually if you need one.
How do I decode Base64 back to text in Swift?+
Use the decode snippet above. Base64 decoding is lossless, so you get the exact original bytes back; decode them with UTF-8 to recover text.
Is Base64 encoding the same across programming languages?+
Yes. Base64 is a standard (RFC 4648), so a string encoded in one language decodes correctly in any other. Only the API differs, not the output.
Does Base64 secure my data?+
No. Base64 is an encoding, not encryption — anyone can decode it. Never use it to protect secrets.