NSCoder and Swift structs and enums

Has anyone of you found a nice way to get NSCoder play along with Swifts structs and enums (In Swift < 2.0) and is willing to share?


I am sitting and trying to get State Restoration working but as I keep some of my states in Structs it is challenging.

Actually I think about just switching to classes wherever I need to restore but actually I do like Structs in those cases.

Replies

See this for the best answer we were able to come up with: https://forums.developer.apple.com/thread/7729


In-depth discussion: https://forums.developer.apple.com/thread/7370


EDIT: Ooop, sorry, I missed the "In Swift < 2.0" part. The linked solution above relies on Swift 2.0

I think the should not use value types to this purpose. For simplest cases ok, but complex ones....? Will be the **** to maintain.

Its better make a class handler or something else to load/store yours value types, like you do for databases for example.

Don't fight with type system.

I'm not sure if I understand you correctly.


For what purposes I should not use value types?

And how do Ifight the type system by using structs to keep (e.g.) the user position (-> CLLocationCoordinate2D)? NSCoder ignores half of the Swift type system by restricting to AnyObject.

NSCoder is ObjectiveC and can't handly pure Swift types because of this.

I think you might try extending NSCoder to handle your value type. Something like


import Foundation


struct T {

var x: Int

init(_ _x: Int) { x = _x }

}


extension NSCoder {

func decodeTForKey(key: String) -> T {

let x = self.decodeIntegerForKey("\(key).x")

return T(x)

}

func encodeT(t: T, forKey key: String) {

self.encodeInteger(t.x, forKey: "\(key).x")

}

}


where T is your value type. I haven't tested this, but it might work. It, at least, compiles using Swift 1.2.


I'm brand new to Cocoa and Swift, so beg pardon if this isn't on the right track.

I generally make my value types conform to RawRepresentable, using types that can be coded (dictionaries and arrays of strings, numbers, booleans, dates, datas, colors, and so on), and then encode and decode the raw representation. (As a reminder, you get RawRepresentable conformance on a simple enum just by making your enum "inherit" from a type like Int.)