Making structs serializable

Just for completeness I’d like to show in this post how to make structs serializable in the same manner as enums (see this post). Again, we transform the struct to a dictionary of NSCoding compliant types and give it to an NSCoder (e.g. NSKeyedArchiver) for coding. The other way round we get the decoded dictionary and initialize the desired struct with it. Sounds simple, doesn’t it. Let’s start.

As for enums we have to implement the protocol „PropertyListReadable“ for our struct. As a reminder here is the protocol definition:

As an example let’s create a struct „Person“ that contains a name, an age and the mood of a person. The mood should be represented by the enum „Happiness2“ from my previous posts. So you can see that this mechanism can be nested as well.

Let’s look at the encoding part first (lines 26 – 32). Here we have to transform the struct to a dictionary of NSCoding compliant types. Every property will be an entry in the dictionary with an identifying key (String) and its value. For the name (String) and the age (Int) that’s simple. The mood is an enum and its value is not NSCoding compliant by itself. But since we have made „Happiness2“ PropertyListReadable we can put its perpertyListRepresentation into the dictionary.

For the init part (lines 12 – 24) we make it the other way round. First we have to check that we’ve really got a dictionary for initializing the struct. Then we pick one by one the properties from the dictionary and fill the struct. For the property mood we do not get the enum itself from the dictionary but its propertyListRepresentation. From that we can initialize the enum mood. That’s it.

Let’s make a check and create an instance of our struct, encode it and decode it finally.

Everything works fine. The decoded object is equal to the original one. Here is the playground of this example:


Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert