Byte Level File I/O in Swift

So, one of the first things I wanted to do in Swift was to start to port the Java model of XML over to Swift. But to do that I needed to be able to read the XML files as a series of bytes so that I could convert all the various character encodings (UTF-8, UTF-16, ASCII, Latin-1, Windows-1252, etc.) into Swift Strings. I also wanted to be able to process the XML files in small chunks to accommodate very large XML files without devouring all of the computer’s memory.

So, the best way that I found to do it is by using the FileHandle class. This class allows reading and writing to/from the disk or network (or, really, anything that provides a file handle from the OS). It has convenience initializers for file paths and URLs. It also allows for reading/writing asynchronously on threads.

Here’s a little test I did in the Playground:

import Foundation

let testDir: String = "/Users/grhodes/Desktop/14 March 2020/XML"
let testFile: String = testDir + "/Test4.xml"

if let handle: FileHandle = FileHandle(forReadingAtPath: testFile) {
    print("Opened file for reading: \(testFile)")

    do {
        if let data: Data = try 10) {
            print("Read \(data.count) bytes: \(String(data: data, encoding: String.Encoding.utf8) ?? "---")")
        try handle.close()
    catch let error {
        print("ERROR: \(error)")
else {
    print("Failed to open file: \(testFile)")

Leave a Reply