Base64 Encode and Decode in Swift

I wrote Base64 encode and decode routines for Objective-C in the recent past. Let’s give it a go with Swift.

Below is a first pass – I used the same test string from the original Objective-C version to verify the results are as expected.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var str = "iOS Developer Tips encoded in Base64"
println("Original: \(str)")
 
// UTF 8 str from original
// NSData! type returned (optional)
let utf8str = str.dataUsingEncoding(NSUTF8StringEncoding)
 
// Base64 encode UTF 8 string
// fromRaw(0) is equivalent to objc 'base64EncodedStringWithOptions:0'
// Notice the unwrapping given the NSData! optional
// NSString! returned (optional)
let base64Encoded = utf8str.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!)
println("Encoded:  \(base64Encoded)")
 
// Base64 Decode (go back the other way)
// Notice the unwrapping given the NSString! optional
// NSData returned
let data = NSData(base64EncodedString: base64Encoded, options: NSDataBase64DecodingOptions.fromRaw(0)!)
 
// Convert back to a string
let base64Decoded = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Decoded:  \(base64Decoded)")

The output is as follows:

Original: iOS Developer Tips encoded in Base64
Encoded: aU9TIERldmVsb3BlciBUaXBzIGVuY29kZWQgaW4gQmFzZTY0
Decoded: iOS Developer Tips encoded in Base64

Referring back to the Objective-C version you’ll notice the values are the same.

Swift Type Inference

Type inference is a huge feature in Swift. Notice above on lines 6, 12, 18 and 21 how Swift inferred the types based on the return values. For completeness, the type-defined and the inferred versions are shown below.

let utf8str: NSData = str.dataUsingEncoding(NSUTF8StringEncoding)
let utf8str = str.dataUsingEncoding(NSUTF8StringEncoding)
 
let base64Encoded:NSString = utf8str.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!)
let base64Encoded = utf8str.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!)
 
let data: NSData = NSData(base64EncodedString: base64Encoded, options: NSDataBase64DecodingOptions.fromRaw(0)!)
let data = NSData(base64EncodedString: base64Encoded, options: NSDataBase64DecodingOptions.fromRaw(0)!)
 
let base64Decoded: NSString = NSString(data: data, encoding: NSUTF8StringEncoding)
let base64Decoded = NSString(data: data, encoding: NSUTF8StringEncoding)
  1. I believe you can also use
    utf8str.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)

    and

    NSData(base64EncodedString: self, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)

    and not have to deal with the unwrapping and fromRaw(0)

    Also allows for auto-complete to help

Comments are closed.