Dictionary Swift 2.0字典KVC扩展

Dictionary Swift 2.0字典KVC扩展,dictionary,swift2,protocols,kvc,Dictionary,Swift2,Protocols,Kvc,我正在尝试实现字典扩展以符合KVC协议: protocol KVCodeable { func valueForKeyPath(keyPath: String) -> AnyObject? } 这样做的原因是,我希望能够从NSManagedObject或字典中获取值 所以我要定义一个模型对象: var modelObject: KVCodeable? 稍后,我将访问该模型对象,尝试获取一个值: let value: AnyObject? = modelObject?.value

我正在尝试实现字典扩展以符合KVC协议:

protocol KVCodeable {
    func valueForKeyPath(keyPath: String) -> AnyObject?
}
这样做的原因是,我希望能够从NSManagedObject或字典中获取值

所以我要定义一个模型对象:

var modelObject: KVCodeable?
稍后,我将访问该模型对象,尝试获取一个值:

let value: AnyObject? = modelObject?.valueForKeyPath(keyPath)
我的模型对象在某些情况下是一个NSManagedObject,在其他一些情况下,它是一个swift字典或其派生

extension NSManagedObject: KVCodeable {} //already done

                 : KVCodeable
                   \/
extension Dictionary where Key: String {
    func valueForKeyPath(keyPath: String) -> AnyObject? {
        return self[keyPath]
    }
}
如何定义dictionary where Key:String的扩展以符合KVCodable

谢谢
罗尼

这是可行的,但不是最好的解决方案

extension Dictionary:KVCodeable {
    public func valueForKeyPath(keyPath: String) -> AnyObject? {
        return self[keyPath as! Key] as? AnyObject
    }
}

这个问题不能作为一个整体来解决,但有两个半解决方案:

1) 扩展所有词典:

extension Dictionary: KVCodeable {
    func valueForKeyPath(keyPath: String) -> AnyObject? {
        guard let key = keyPath as? Key else { return nil }
        return self[key] as? AnyObject
    }
}
2) 仅扩展特定词典,但必须删除与
KVCodeable
的一致性:

// You have to make this protocol since:
// extension Dictionary where Key == String { ... }
// is currently not allowed
protocol StringType { var string: String { get } }
extension String: StringType { var string: String { return self } }

extension Dictionary where Key: StringType, Value: AnyObject {
    func valueForKeyPath(keyPath: String) -> AnyObject? {
        guard let key = keyPath as? Key else { return nil }
        return self[key] as? AnyObject
    }
}

总之,第一种可能是最好的。否则,您也可以将该函数设置为抛出函数,以便捕获“错误”的词典。

true,工作正常,但有潜在危险。。。可以这样做:如果让k=key as?键{return self[k]as?AnyObject}但本质上这将扩展所有字典类型,我的目标是找到类型Yep的一个,我想现在可能是一个快速的限制。我不能让它只适用于特定的字典类型。