字典需要扩展以获取文本键值(如果存在)。
执行以下代码并成功编译:
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/