AAV AAV - 1 month ago 24
Swift Question

Any way to store struct in NSCache

Is there any way to store struct values in NSCache ? When I read the apple documentation look like you can only store AnyObject to it. There are couple of work around one is convert sturct to class, second convert sturct values to the dictionary but they are very expensive operation if dataset is big. Any suggestion?

Answer

I'm going to chance my arm on a 'no' (without workarounds). NSCache is resoundingly over on the Objective-C side of the runtime, written to work with NSObjects, bridged via AnyObject. Unlike NSDictionary and NSArray there is no equivalent Swift collection that the compiler can bridge between.

Implementation points aside: NSCache simply doesn't live in a world that understands value semantics for anything more sophisticated than C atoms.

That being said, probably the easiest workaround is just to create an object container for your struct, making the bridging explicit but owned by whomever wants to use the cache:

class YourStructHolder: NSObject {
    let thing: YourStruct
    init(thing: YourStruct) {
        self.thing = thing
    }
}

cache.setObject(YourStructHolder(thing: thing), forKey:"Whatever")
(cache.objectForKey("Whatever") as? YourStructHolder)?.thing

... or skip the init and use a var ...: YourStruct? if you're happy with mutability. You're going to have to deal with optionality when talking to the cache anyway.