Swift 4’s new Codable protocol makes it much simpler to serialize Swift objects. The built-in JSONEncoder and PlistEncoder encode and decode JSON and plist, but what about when you need to use other formats?
Writing a custom encoder is fairly complex, so Serializer takes care of that for you. Serializer converts your Swift objects into a simple enum, which you can easily traverse and write to a file format of your choice.
All you have to do is implement the Serializer protocol and create a method called serialize, which encodes a Serializable enum into your custom format. Decoding is similar – add the Deserializer protocol, with a deserialize method which converts your custom format into a Serializable. Here’s an example serializer and deserializer for the NBT file format.
Serializer
Swift 4’s new
Codable
protocol makes it much simpler to serialize Swift objects. The built-inJSONEncoder
andPlistEncoder
encode and decode JSON and plist, but what about when you need to use other formats?Writing a custom encoder is fairly complex, so Serializer takes care of that for you. Serializer converts your Swift objects into a simple
enum
, which you can easily traverse and write to a file format of your choice.All you have to do is implement the
Serializer
protocol and create a method calledserialize
, which encodes aSerializable
enum into your custom format. Decoding is similar – add theDeserializer
protocol, with adeserialize
method which converts your custom format into aSerializable
. Here’s an example serializer and deserializer for the NBT file format.