Writing Files in Swift

Here’s the translation of the Go code to Swift, along with explanations in Markdown format suitable for Hugo:

Writing files in Swift follows similar patterns to the ones we saw earlier for reading.

import Foundation

func check(_ error: Error?) {
    if let error = error {
        fatalError(error.localizedDescription)
    }
}

// To start, here's how to dump a string (or just bytes) into a file.
let d1 = "hello\nswift\n"
do {
    try d1.write(toFile: "/tmp/dat1", atomically: true, encoding: .utf8)
} catch {
    check(error)
}

// For more granular writes, open a file for writing.
let fileURL = URL(fileURLWithPath: "/tmp/dat2")
let f = try! FileHandle(forWritingTo: fileURL)

// It's idiomatic to defer a close immediately after opening a file.
defer {
    f.closeFile()
}

// You can write Data as you'd expect.
let d2 = Data([115, 111, 109, 101, 10])
f.write(d2)
print("wrote \(d2.count) bytes")

// A write(String:) method is also available.
let d3 = "writes\n"
if let d3Data = d3.data(using: .utf8) {
    f.write(d3Data)
    print("wrote \(d3Data.count) bytes")
}

// Issue a synchronize to flush writes to stable storage.
f.synchronize()

// FileHandle provides buffered writers in addition to the buffered readers we saw earlier.
let d4 = "buffered\n"
if let d4Data = d4.data(using: .utf8) {
    f.write(d4Data)
    print("wrote \(d4Data.count) bytes")
}

// Use synchronize to ensure all buffered operations have been applied to the underlying file.
f.synchronize()

Try running the file-writing code.

$ swift writing-files.swift
wrote 5 bytes
wrote 7 bytes
wrote 9 bytes

Then check the contents of the written files.

$ cat /tmp/dat1
hello
swift
$ cat /tmp/dat2
some
writes
buffered

Next we’ll look at applying some of the file I/O ideas we’ve just seen to the stdin and stdout streams.