Last active
July 26, 2019 05:53
-
-
Save tkrajacic/7fc46f0c3a821fc238439f5b631e1058 to your computer and use it in GitHub Desktop.
Trying to create an array that automatically persists to a JSON file on disk
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
public final class PersistedArray<T: Codable> { | |
private var array: [T] { | |
didSet { | |
do { | |
try save() | |
} catch { | |
print("\(error)") | |
} | |
} | |
} | |
private var url: URL = URL(string: "/dev/null")! | |
var decoder: JSONDecoder = { | |
let decoder = JSONDecoder() | |
decoder.dateDecodingStrategy = .iso8601 | |
return decoder | |
}() | |
var encoder: JSONEncoder = { | |
let encoder = JSONEncoder() | |
encoder.dateEncodingStrategy = .iso8601 | |
return encoder | |
}() | |
// public init(_ initial: [T] = []) { | |
// array = initial | |
// } | |
public init(url: URL) { | |
self.url = url | |
array = [] | |
// try to load | |
array = (try? load(from: url)) ?? [] | |
} | |
public subscript(index: Int) -> T { | |
get { | |
return array[index] | |
} | |
set { | |
array[index] = newValue | |
} | |
} | |
public func get() -> [T] { | |
return array | |
} | |
// public func append(_ element: T) { | |
// array.append(element) | |
// } | |
private func load(from url: URL) throws -> [T] { | |
if !FileManager.default.fileExists(atPath: url.path) { | |
FileManager.default.createFile(atPath: url.path, contents: nil, attributes: nil) | |
} | |
let data = try NSData(contentsOf: url, options: .uncached) | |
return try decoder.decode([T].self, from: data as Data) | |
} | |
private func save() throws { | |
let data: NSData = try encoder.encode(array) as NSData | |
try data.write(to: url, options: .atomic) | |
} | |
deinit { | |
_ = try? save() | |
} | |
} | |
extension PersistedArray: Collection { | |
public func index(after i: Int) -> Int { | |
return array.index(after: i) | |
} | |
public var startIndex: Int { | |
return array.startIndex | |
} | |
public var endIndex: Int { | |
return array.endIndex | |
} | |
} | |
extension PersistedArray: RandomAccessCollection {} | |
extension PersistedArray: RangeReplaceableCollection { | |
public convenience init() { | |
self.init(url: URL(string: "/dev/null")!) | |
} | |
} | |
var arr = PersistedArray<Int>(url: URL(string: "/dev/null")!) | |
arr.append(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment