Skip to content

Instantly share code, notes, and snippets.

@shmidt
Forked from stinger/Swift3Base64.swift
Last active September 19, 2022 08:18
Show Gist options
  • Save shmidt/2295b52b1e3289672e2ffafd6ca58c60 to your computer and use it in GitHub Desktop.
Save shmidt/2295b52b1e3289672e2ffafd6ca58c60 to your computer and use it in GitHub Desktop.
Swift 3: Base64 encoding and decoding strings
//: # Swift 3: Base64 encoding and decoding
import Foundation
extension String {
//: ### Base64 encoding a string
func base64Encoded() -> String? {
if let data = self.data(using: .utf8) {
return data.base64EncodedString()
}
return nil
}
//: ### Base64 decoding a string
func base64Decoded() -> String? {
if let data = Data(base64Encoded: self, options: .ignoreUnknownCharacters) {
return String(data: data, encoding: .utf8)
}
return nil
}
}
var str = "Hello, playground"
print("Original string: \"\(str)\"")
if let base64Str = str.base64Encoded() {
print("Base64 encoded string: \"\(base64Str)\"")
if let trs = base64Str.base64Decoded() {
print("Base64 decoded string: \"\(trs)\"")
print("Check if base64 decoded string equals the original string: \(str == trs)")
}
}
@dfpalomar
Copy link

Thank you! :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment