Saving Structs in Swift

557 views Asked by At

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?

1

There are 1 answers

3
0x416e746f6e On

As far as I understand the whole NSCoding business is intended and designed for storing/retrieving object trees. Hence the requirement to have NSObject as a base class (perhaps at some point in future it might be moved to AnyObject, 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) and decodeFooForKey(key: String) -> Foo, where Foo would be one of your custom structs, and then use these functions in your classes that implement NSCoding protocol just the same way you would use similar functions for base Obj-C types.