Grant Emerson

Strings to Be Written

Strings to Be Written โ€” SwiftMoji Entry #27

The Foundation framework offers quite a few additional methods to Strings. The write(to:atomically:encoding) instance method can be used to save a String in a file. The to parameter is of type URL and specifies the location for which the String is to be saved. The atomically parameter specifies whether or not an intermediate file should be used during the writing process. If it is set to true, an intermediate file is used to protect any existing files from corruption due to a crash. Lastly, the encoding parameter specifies how the Stringโ€™s characters should be stored in memory. The utf8 encoding method is by far the most common for Unicode and is recommended for most operations. Beware, a call to write must be wrapped in a do-catch statement to handle any errors that might occur during the process.

import Foundation

let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let url = documentsDirectory.appendingPathComponent("Closet Contents").appendingPathExtension("txt")

var closet = "๐Ÿ‘–x2 ๐Ÿ‘•x5 ๐Ÿ‘”x3 ๐Ÿ‘Ÿx2 ๐Ÿ‘žx2"

do {
    try closet.write(to: url, atomically: true, encoding: .utf8)
} catch {
    print("Error writing string to disk: \(error.localizedDescription).")
}
Tagged with: