使用扩展中的键对Swift字典进行访问 [英] Swift Dictionary access value using key within extension

查看:86
本文介绍了使用扩展中的键对Swift字典进行访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

事实证明,在Dictionary扩展中,下标非常有用,因为它标明Ambiguous reference to member 'subscript'.看来我要么要做Swift在其subscript(Key)中所做的事情,要么调用一个函数.有什么想法吗?

It turns out that within a Dictionary extension, the subscript is quite useless since it says Ambiguous reference to member 'subscript'. It seems I'll either have to do what Swift does in its subscript(Key) or call a function. Any ideas?

例如,

public extension Dictionary {
    public func bool(_ key: String) -> Bool? {
        return self[key] as? Bool
    }
}

不起作用,因为据说下标是模棱两可的.

won't work, since the subscript is said to be ambiguous.

添加我的误解来自以下事实:我认为KeyAssociatedType而不是通用参数.

ADDED My misunderstanding came from the fact that I assumed that Key is an AssociatedType instead of a generic parameter.

推荐答案

快速类型Dictionary具有两个通用参数KeyValue,而Key可能不是String.

Swift type Dictionary has two generic parameters Key and Value, and Key may not be String.

这有效:

public extension Dictionary {
    public func bool(_ key: Key) -> Bool? {
        return self[key] as? Bool
    }
}

let dict: [String: Any] = [
    "a": true,
    "b": 0,
]
if let a = dict.bool("a") {
    print(a) //->true
}
if let b = dict.bool("b") {
    print(b) //not executed
}


对于 ADDED 部分.


For ADDED part.

如果在Dictionary的扩展名中引入了新的通用参数T,则方法需要适用于Key(:Hashable),ValueT(:Hashable). KeyT可能不是同一类型.

If you introduce a new generic parameter T in extension of Dictionary, the method needs to work for all possible combination of Key(:Hashable), Value and T(:Hashable). Key and T may not be the same type.

(例如,Key可能是String,而T可能是Int(都是Hashable).您知道当KeyString时不能用Int下标.)

(For example, Key may be String and T may be Int (both Hashable). You know you cannot subscript with Int when Key is String.)

因此,您不能使用T类型的key下标.

So, you cannot subscript with key of type T.

有关更新的添加部分.

似乎是一种合理的误解.而且您已经找到了一个很好的示例,可以说明具有关联类型的协议不仅仅是通用协议.

Seems to be a reasonable misunderstanding. And you have found a good example that explains protocol with associated type is not just a generic protocol.

这篇关于使用扩展中的键对Swift字典进行访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆