others-Example of swift String extension to do Base64 encoding and decoding

1. Purpose

In this post, I would demo how to do base64 encode and decode using swift language.

2. Environment

  • Mac OS
  • Xcode
  • Swift 5

3. The solution

3.1 Example 1

import UIKit
import Foundation

extension String {
    func encodeBase64() -> String {
        if let data = self.data(using: .utf8) {
            return data.base64EncodedString()
        }
        return ""
    }
    
    func decodeBase64() -> String {
        if let data = Data(base64Encoded: self) {
            return String(data: data, encoding: .utf8)!
        }
        return ""
    }
}

Test code:

var s1:String = "test_group_20210815185842"
var s2 = s1.encodeBase64()
print("base64 encoded:\(s2)")
print("base64 decoded: \(s2.decodeBase64())")

We got this result:

base64 encoded:dGVzdF9ncm91cF8yMDIxMDgxNTE4NTg0Mg==
base64 decoded: test_group_20210815185842

3.2 Example 2

Here is the example that returns an optional result:

import UIKit
import Foundation

extension String {
	  func encodeBase64() -> String? {
        if let data = self.data(using: .utf8) {
            return data.base64EncodedString()
        }
        return nil
    }
    
    func decodeBase64() -> String? {
        if let data = Data(base64Encoded: self) {
            return String(data: data, encoding: .utf8)
        }
        return nil
    }
}

4. Summary

In this post, I demonstrated how to do base64 encoding and decoding using swfit extension .