gpt4 book ai didi

ios - 在 swift 扩展中重载 NSDictionary getter

转载 作者:行者123 更新时间:2023-11-30 14:15:46 25 4
gpt4 key购买 nike

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

最佳答案

也许你想要这样的东西

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"

关于ios - 在 swift 扩展中重载 NSDictionary getter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31212885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com