Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift enum and NSCoding

I have a 'Thing' object with a String property and an NSImage property; the Thing class has encodeWithCoder: and decodeWithCoder: methods, and I can archive and unarchive a [Thing] array using NSKeyedArchiver/Unarchiver.

So far, so good. Now I want to expand my Thing class by an array of directions, where 'Direction' is the following enum:

enum Direction{

case North(direction:String)
case East(direction:String)
case South(direction:String)
case West(direction:String)

}

In other words, the data I wish to store is

thing1.directions: Direction = [.North("thing2"), .South("thing3")]

(In a more perfect world, I'd be using direct references to my Things rather than just their names, but I realise that this will easily create reference cycles - can't set a reference to another Thing until that Thing has been created - so I'll refrain. I'm looking for a quick and dirty method to save my app data and move on.)

Since I will be needing directions elsewhere, this is a separate entity, not just an enum inside the Thing class. (Not sure whether that makes a difference.)

What is the best way to make my Direction enum conform to NSCoding? The best workaround I can come up with involves creating a [String: String] dictionary with "North" and "South" as keys and "thing2" and "thing3" as values, and reconstruct my enum property from that, but is there a better way? And for that matter, is there a way to make tuples conform to NSCoding because right now (String, String) gets me a 'not compatible to protocol "AnyObject"' error.

Many thanks.

like image 860
green_knight Avatar asked Mar 19 '23 03:03

green_knight


1 Answers

What I do is give the enum a type and encode and decode its raw value, or else implement description for the enum and encode and decode that string. Either way (or if you use some other way), you obviously need a way to convert in both directions between an enumerator and an archivable type.

like image 65
matt Avatar answered Apr 02 '23 09:04

matt