swift - 在 Swift 中获取错误 Ambiguous reference to member 'subscript'

标签 swift dictionary swift3

字典需要扩展以获取文本键值(如果存在)。

执行以下代码并成功编译:

extension Dictionary where Key: ExpressibleByStringLiteral, Value: AnyObject {
    func getValueForKeyPath(keyValue: String) -> String {
        return ((self["item_qty"] as? Dictionary<String, String>) ?? ["": ""])?["text"] ?? ""
    }
}

但是当我对方法做一些小改动时,出现错误:

"Ambiguous reference to member 'subscript' "

extension Dictionary where Key: ExpressibleByStringLiteral, Value: AnyObject {
    func getValueForKeyPath(keyValue: String) -> String {
        return ((self[keyValue] as? Dictionary<String, String>) ?? ["": ""])?["text"] ?? ""
    }
}

如果我在这里做错了什么,请纠正我。

最佳答案

尝试将 keyValue 转换为 Key。例如:

extension Dictionary where Key: ExpressibleByStringLiteral, Value: AnyObject {
    func getValueForKeyPath(keyValue : String) -> String{
        return ((self[keyValue as! Key] as? Dictionary<String,String>) ?? ["":""])?["text"] ?? ""
    }
}

关于swift - 在 Swift 中获取错误 Ambiguous reference to member 'subscript',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40377267/

相关文章:

ios - 为什么从 FileManager 数据初始化的 UIImages 有错误的比例?

ios - NSNotificationCenter 将选择器发送到错误的实例

ios - 使用 RXSwift 观察 contentSize 时检测到重入异常

python - 通过 dict of dict of dict 计算值

ios - 创建检查将产生错误的按钮(swift3)

Bundle的Swift 3示例(对于: XXX)

swift - 将枚举类型的值与关联值进行比较时出现编译器错误?

swift - 我如何比较 Swift 3 中的两个日期 (NSDate) 并获得它们之间的日期?

Python - For循环不会用它的匹配值替换每个字典键...仅与字典中的最后一个键和值合作

dictionary - 分配给映射键多少内存?即map [uint16] uint16是每个键2个字节还是存储为uint32/64?