Skip to content
Norman Basham edited this page Feb 17, 2020 · 1 revision

File

Utilities for loading, saving, and checking existence of project files. Saving and loading are done without requiring Codable. The examples below assume a project containing a file named quotes.txt. Code relies on Bundle.main so it will need to be modified for use when UI or unit testing.

Get Data from a file:

  let data = Data(localFile: "quotes.txt")

Load a file and parse it:

let quotes: [String] = Data.parse(localFile: "quotes.txt") { str in
    let lines = str.components(separatedBy: CharacterSet.newlines).filter { $0.count > 0 }
    return lines.compactMap { $0.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) }
}

Load a file into an array of String filtering whitespace lines and trimming whitespace from beginning and end:

let quotes: [String]? = Data.lines(localFile: "quotesWithEmptyLines.txt")

Save a file to iOS Documents directory:

let str = "Hi there"
DocumentsFile.save(str, fileName: "fileName.ext")

See if a file exists in the iOS Documents directory:

DocumentsFile.exists("fileName.ext")

Load a file from the iOS Documents directory:

let obj = DocumentsFile.load("fileName.ext") as? String

Save a file to iOS App Support directory:

let str = "Hi there"
AppSupportFile.save(str, fileName: "fileName.ext")

See if a file exists in the iOS App Support directory:

AppSupportFile.exists("fileName.ext")

Load a file from the iOS App Support directory:

let obj = AppSupportFile.load("fileName.ext") as? String