Support Decodable/Encodable (Swift 4)
phimage opened this issue · comments
In the past, I try to make some utility functions to work with NSCoding (branch feature-nscoding), write and read JSON
In swift 4 Decodable/Encodable (and Codable) allow to have a better interface to serialize objects
We can
- write to file an
Encodable
object - write to file an array of
Encodable
objects - read from file an
Decodable
object - read from file an array of
Decodable
objects
That could be done only after merging #49
These would be good changes to have but behind #if swift(>=3.2)
.
I make a class FileKit to get shared JSON/PropertyList encoder/decoder
And also for easy to use functions
try FileKit.write(encodable, to: .userTemporary + "test")
let decodable: MyClass = try FileKit.read(from: .userTemporary + "test")
Array of Codable are codable, so the same functions work
I add protocols JSONReadable
, JSONWritable
(or PropertyListReadable
/PropertyListWritable
) to be able to implement Readable
and Writable
and create File
with specific type just by implementing protocols
(an alias name could be added like JSONReadableWritable
if necessary for JSONWritable, JSONReadable)
This protocol define the encoder or decoder to use. By default the one shared by FileKit
struct TestJSONCodable: Codable {
let string: String
let integer: Int
}
extension TestJSONCodable: JSONWritable, JSONReadable {}
let encodable = TestJSONCodable(string: "test", integer: 9)
let codableFile = File<TestJSONCodable>(path: .userTemporary + "testcodable.json")
try codableFile.write(encodable)
let decodable: TestJSONCodable = try codableFile.read()
committed but need some doc in README