我最近能够从以下位置更改扩展名:
extension Array where Element: Encodable { ... }
Run Code Online (Sandbox Code Playgroud)
至:
extension CollectionType where Generator.Element: Encodable { ... }
Run Code Online (Sandbox Code Playgroud)
为了以后能够与应用类型约束CollectionType和Encodable在不同的扩展名.
现在我正在尝试做同样的事情Dictionary,改变:
extension Dictionary where Key: StringLiteralConvertible, Value: Encodable { ... }
Run Code Online (Sandbox Code Playgroud)
至:
extension CollectionType where Generator.Element == (Key: StringLiteralConvertible, Value: Encodable) { ... }
Run Code Online (Sandbox Code Playgroud)
但是,后者似乎不是该Dictionary类型的有效替代,因为现在扩展中定义的方法不能在字典上调用.
如何定义CollectionType(或可能SequenceType)扩展名以使其方法可用于词典?
更新
我想要注意,我已尝试添加类型约束,如下所示,但没有成功:
extension CollectionType where Self: protocol<Indexable, SequenceType, DictionaryLiteralConvertible>, Self.Key: protocol<Hashable, StringLiteralConvertible>, Self.Value: Encodable, Self.Generator.Element == (Key: StringLiteralConvertible, Value: Encodable) { ... }
Run Code Online (Sandbox Code Playgroud)
更新2
因为user2194039问 - 我不想这样做,并保持扩展名Array和Dictionary.
但是,我还需要为Optional变体编写扩展.我的理解是,由于它们使用了泛型,因此不可能为Optional它约束Array或者编写类型约束Dictionary.
这适用于我当前的用例:
extension CollectionType where Self: DictionaryLiteralConvertible, Self.Key: StringLiteralConvertible, Self.Value: Encodable, Generator.Element == (Self.Key, Self.Value) { ... }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1305 次 |
| 最近记录: |