NSCache access through index in Swift 3

Many developers like to extend NSCache to make it compatible with signatures, using something like a code snippet here, but this has stopped working in Swift 3. Currently, a known bug is being tracked here on Swift.org . In the meantime, did anyone find another way to get the same result? I do not want to change my entire code base, but I also do not know how soon this error will be fixed.

// Allows using subscripts on NSCache, like a dictionary extension NSCache { subscript(key: AnyObject) -> AnyObject? { get { return object(forKey: key as! KeyType) } set { if let value: AnyObject = newValue { setObject(value as! ObjectType, forKey: key as! KeyType) } else { removeObject(forKey: key as! KeyType) } } } 
+6
source share
1 answer

Possible workarounds to the SR-2104 are fixed:

Option 1

If you can replace cache objects with an arbitrary class, and not inherit from NSCache , then you can wrap NSCache in a common container and forward the necessary methods:

 class WrappedCache<Key, Value> where Key: AnyObject, Value: AnyObject { let cache = NSCache<Key, Value>() subscript(key: Key) -> Value? { get { return cache.object(forKey: key) } set { if let newValue = newValue { cache.setObject(newValue, forKey: key) } else { cache.removeObject(forKey: key) } } } } 

You can avoid passing the internal cache value if necessary.

Option 2

When you must reference NSCache and have a limited number of specific cache types, you can specialize them, and each of them has its own implementation of the substring:

 class NumberCache : NSCache<NSString, NSNumber> { subscript(key: NSString) -> NSNumber? { get { return object(forKey: key) } set { if let newValue = newValue { setObject(newValue, forKey: key) } else { removeObject(forKey: key) } } } } 
+2
source

All Articles