我最近能够更改扩展名:
extension Array where Element: Encodable { ... }
to:
extension CollectionType where Generator.Element: Encodable { ... }
为了以后能够应用类型约束CollectionType
and Encodable
在不同的扩展中。
现在我正在尝试做同样的事情Dictionary
,改变:
extension Dictionary where Key: StringLiteralConvertible, Value: Encodable { ... }
to:
extension CollectionType where Generator.Element == (Key: StringLiteralConvertible, Value: Encodable) { ... }
然而,后者似乎不能有效替代Dictionary
类型,因为现在无法在字典上调用扩展中定义的方法。
我如何定义一个扩展CollectionType
(或者可能SequenceType
)以便它的方法可用于字典?
Update
我想指出的是,我尝试添加类型约束如下,但没有成功:
extension CollectionType where Self: protocol<Indexable, SequenceType, DictionaryLiteralConvertible>, Self.Key: protocol<Hashable, StringLiteralConvertible>, Self.Value: Encodable, Self.Generator.Element == (Key: StringLiteralConvertible, Value: Encodable) { ... }
Update 2
由于 user2194039 询问 – 我不想这样做并保留扩展名Array
and Dictionary
.
但是,我还需要为Optional
变体。我的理解是,由于他们使用泛型,不可能为Optional
这限制了它Array
or Dictionary
.