-
Notifications
You must be signed in to change notification settings - Fork 0
File
Norman Basham edited this page Feb 17, 2020
·
1 revision
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.
let data = Data(localFile: "quotes.txt")
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")
let str = "Hi there"
DocumentsFile.save(str, fileName: "fileName.ext")
DocumentsFile.exists("fileName.ext")
let obj = DocumentsFile.load("fileName.ext") as? String
let str = "Hi there"
AppSupportFile.save(str, fileName: "fileName.ext")
AppSupportFile.exists("fileName.ext")
let obj = AppSupportFile.load("fileName.ext") as? String