在 swift 扩展中重载 NSDictionary getter

Overload NSDictionary getter in swift extension

我想使用 mu 自定义枚举作为我的字典的键。到目前为止我这样做了:

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 方法上使用我的自定义枚举。

为什么不呢?您甚至不必为 NSDictionary:

添加扩展名
enum DBKeys : String {
    case Key1 = "Key1", Key2 = "key2", Key3 = "key3"
}

var dic = [DBKeys : String]()

dic[.Key1] = "hello world"
println(dic[.Key1]!) // hello world

也许你想要这样的东西

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"