FileBackedDictionary
public struct FileBackedDictionary<T> where T : Decodable, T : Encodable
Encapsulates a [String:T]
dictionary whose values are automatically persisted (each in its own file).
Exposes methods and properties similar to those of the Swift Dictionary.
Usage examples:
Create a FileBackedDictionary
instance, using Documents subdirectory named Resources
and struct Resource
as the value type.
let directoryName = "Resources"
var fbDict = FileBackedDictionary<Resource>(directoryName: directoryName)
Add resource instances
fbDict["apples"] = Resource(name: "apples", value: 1, quantity: 1)
fbDict["oranges"] = Resource(name: "oranges", value: 2, quantity: 2)
fbDict["mangos"] = Resource(name: "mangos", value: 3, quantity: 3)
Look up the resource info
let count = bDict.count // 3
let keys = fbDict.keys // ["apples", "oranges", "mangos"])
let values = fbDict.values // ...
let myOranges = fbDict["oranges"]
Remove resources
fbDict["oranges"] = nil
fbDict.removeAll()
At its initialization (typically at the application start), an instance of FileBackedDictionary
recovers the keys and values from the file storage.
-
Declaration
Swift
private(set) var dictionary: [String : T] { get }
-
Initialize the backed-up storage
Remark
if the directory for the backup files does not exist, creates it. Initiallizes the local dict from files in the directory (if any)Declaration
Swift
public init(directoryName: String)
Parameters
directoryName
names the backup directory
-
Support for dictionary style setting and getting of a value by key
Declaration
Swift
public subscript(key: String) -> T? { get set }
-
Return sorted keys
Declaration
Swift
public var keys: [String] { get }
-
Return values sorted by keys
Declaration
Swift
public var values: [T] { get }
-
Remove the value for key from the dictionary and from the file
Declaration
Swift
public mutating func removeValue(forKey key: String)
Parameters
forKey
key
-
Remove all values from dictionary and from files
Declaration
Swift
public mutating func removeAll()
-
Return the dictionary item count
Declaration
Swift
public var count: Int { get }