我想使用mu custom enum作为我字典的关键字。到目前为止,我做到了这一点:
extension NSDictionary {
enum DBKeys : String {
case Key1 = "Key1", Key2 = "key2", Key3 = "key3"
}
func valueForKey(key : DBKeys) -> AnyObject? {
return self[key.rawValue]
}
}
这是允许我做这样的事情:
let dic = NSDictionary()
dic.valueForKey(.Key1)
但我想要实现的是直接使用getter并编写如下内容:
let dic = NSDictionary()
dic[.Key1]
那么如何直接在我的NSDictionary getter方法中使用我的自定义枚举。
答案 0 :(得分:0)
为什么不呢?您甚至不必向NSDictionary
添加扩展程序:
enum DBKeys : String {
case Key1 = "Key1", Key2 = "key2", Key3 = "key3"
}
var dic = [DBKeys : String]()
dic[.Key1] = "hello world"
println(dic[.Key1]!) // hello world
答案 1 :(得分:0)
也许你想要这样的东西
extension NSDictionary {
enum DBKeys : String {
case Key1 = "Key1", Key2 = "Key2", Key3 = "Key3"
}
subscript (key: DBKeys) -> AnyObject? {
get {
return self[key.rawValue]
}
}
}
let dic = NSDictionary(objects: ["Alpha", "Beta"], forKeys: ["Key1", "Key2"])
dic[.Key1] // "Alpha"