swift - 在 Swift 3 中通过下标访问 NSCache

标签 swift

许多开发者喜欢扩展 NSCache 以使其与下标兼容,使用类似于此处的代码片段,但这在 Swift 3 中已停止工作。目前这是一个正在跟踪的已知错误 here on Swift.org .与此同时,有没有人找到另一种方法来获得相同的结果?我不想更改我的整个代码库,但我也不知道这个错误多久能得到解决

// 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)
        }
    }
}

最佳答案

可能的解决方法直到 SR-2104是固定的:

选项 1

当你可以用任意类代替缓存对象,而不是从 NSCache 继承时,你可以将 NSCache 包装在一个通用容器中,并转发必要的方法:

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)
            }
        }
    }
}

如果必须的话,您可能会传递内部 cache 值。

选项 2

当您必须引用NSCache,并且特定缓存类型的数量有限时,您可以对它们进行特殊化,每一种都有自己的下标实现:

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)
            }
        }
    }
}

关于swift - 在 Swift 3 中通过下标访问 NSCache,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39573643/

相关文章:

ios - 如何从富文本格式文件(如(.doc、.pages、.docx 等))中解析文本

ios - 如何定义一个符合协议(protocol)的对象数组?

Swift,自定义单元格颜色不适用于披露指示器

ios - Uber 身份验证失败 "HTTP Status 401: Unauthorized, Response: {"错误“: "invalid_client"}"

swift - 在堆栈数据结构中查找元素 swift 4

ios - iOS 应用程序的应用程序工作流程

swift - NSInvalidArgumentException : How to check script message handler with name when one already exists?

xcode - viewDidLoad() 之后出现意外的打印对话框

ios - 即使在 player.status == .readyToPlay 之后,AVPlayerItem.duration 仍返回 NaN

ios - UIAlertController - 如果第一次解除警报,则不会执行操作