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.
Swift
Serializing enums with associated values
Welcome to this new posts in my series about enums with associated values. In the previous posts we looked at the equatability of enums with associated values. Another problem arises when we want to store enums (maybe as part of the model) on a file or want to send it over a network, let’s say: want to serialize the enum. Although the primitive types as Int and String conform to the NSCoding protocol as well as collections of those types (e.g. Arrays and Dictionaries) enums and structs don’t. And since they are not classes we can also not implement the NSCoding protocol for them. For simple enums we can use its raw values for coding, but that’s not possible for enums with associated values.
Similarity of enums with associated values
If you have read this previous post you have seen how to compare two enums with associated values for equality. The equality included the associated values as well which is only fair. But sometimes you are not interested in the associated values but only want to know, if the two enums are of the same case regardless of the possibly associated values; I call this in the following if they are „similar“.
Equatable enums with associated values
Enums with associated values are a very powerful tool in Swift. You can store context sensitive information along with the value of the enum itself without the need of an additional data structure. But, as of in Swift 3.1, it has some serious limitations. For example, comparisons of enums are not that easy. Let’s look at this simple code: