Having just watched a couple of videos on value types in Swift from WWDC this year,
Building Better Apps With Value Types in Swift
Protocol-Oriented Programming in Swift
I'm finding myself fully ready to embrace value types in my apps. This means fewer Class types and more Structs. But how do I save this data? Previously, with Classes, I'd adopt NSCoding, but that requires that I adopt NSObject, which is going to require that I use a Class rather than a Struct.
Here are the options as I see them:
- If saving is necessary, the model is too complicated for a Struct and should be redesigned as a class
 - Design my own serialization
 - Use a mediator class
 
How should I go about this?
                        
As far as I understand the whole
NSCodingbusiness is intended and designed for storing/retrieving object trees. Hence the requirement to haveNSObjectas a base class (perhaps at some point in future it might be moved toAnyObject, I guess).Therefore, it is a responsibility of each class from such tree to encode/decode values of (some of) its properties, including structs. All of these structs will be inevitably kept as a property of an object at some level, right?
Given the above, I think that the direction to explore would be to extend NSCoder protocol with functions like
encodeFoo(foo: Foo, forKey key: String)anddecodeFooForKey(key: String) -> Foo, whereFoowould be one of your custom structs, and then use these functions in your classes that implementNSCodingprotocol just the same way you would use similar functions for base Obj-C types.