使用扩展中的键对Swift字典进行访问 [英] Swift Dictionary access value using key within extension
问题描述
事实证明,在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.
添加我的误解来自以下事实:我认为Key
是AssociatedType
而不是通用参数.
ADDED My misunderstanding came from the fact that I assumed that Key
is an AssociatedType
instead of a generic parameter.
推荐答案
快速类型Dictionary
具有两个通用参数Key
和Value
,而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
),Value
和T
(:Hashable
). Key
和T
可能不是同一类型.
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
).您知道当Key
是String
时不能用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屋!