Nijar Nijar - 1 month ago 18
Swift Question

In Swift getting error Ambiguous reference to member 'subscript'

Required extension for Dictionary as to get text key value if exist.

Implemented below code and it is successfully compiled:

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


But when I did small change in method getting error as:


"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"] ?? ""
}
}


Please correct me if I am doing anything wrong here.

Hoa Hoa
Answer

try to cast keyValue to Key. For example:

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