4

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?

Community
  • 1
  • 1
promacuser
  • 374
  • 1
  • 15

1 Answers1

1

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.

0x416e746f6e
  • 9,872
  • 5
  • 40
  • 68
  • 1
    Yeah, one of the built-in features of NSCoding is that it doesn't matter if you encode cycles — no matter what your object graph, `NSCoding` will encode each unique object in it only exactly once and not spin off into an infinite loop if you e.g. have a circular linked queue. That means that it is steeped within a world of reference semantics, over in Objective-C land. So giving it a value-or-reference-type makeover would probably be a bit of effort and hasn't happened yet. – Tommy Oct 22 '15 at 18:04
  • @Tommy, with objects it's possible to uniquely identify them by just the pointer. With value-type instances, how is it possible to have them in cycle? No irony, just trying to learn something new. – 0x416e746f6e Oct 22 '15 at 18:16
  • 1
    No, it's not possible to have a cycle with value semantics. All I meant was: the keyed archiver has a purely Objective-C world view and updating would be a hassle due to the semantic differences. So Apple hasn't, yet. I was agreeing with your first sentence about original intention and design, while speculating on why Apple hasn't moved on from the original design as of the time of writing. – Tommy Oct 22 '15 at 18:23