加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – 如何定义CollectionType的扩展名以使其方法可用于词典

发布时间:2020-12-14 02:23:43 所属栏目:百科 来源:网络整理
导读:我最近能够从以下位置更改扩展名: extension Array where Element: Encodable { ... } 至: extension CollectionType where Generator.Element: Encodable { ... } 以便以后能够在不同的扩展中应用CollectionType和Encodable的类型约束. 现在我正在尝试用D
我最近能够从以下位置更改扩展名:
extension Array where Element: Encodable { ... }

至:

extension CollectionType where Generator.Element: Encodable { ... }

以便以后能够在不同的扩展中应用CollectionType和Encodable的类型约束.

现在我正在尝试用Dictionary做同样的事情,改变:

extension Dictionary where Key: StringLiteralConvertible,Value: Encodable { ... }

至:

extension CollectionType where Generator.Element == (Key: StringLiteralConvertible,Value: Encodable) { ... }

但是,后者似乎不是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) { ... }

更新2

因为user2194039问 – 我不想这样做,并保持对数组和字典的扩展.

但是,我还需要为Optional变体编写扩展.我的理解是,由于它们使用了泛型,因此不可能为Optional编写一个类型约束,将其约束为Array或Dictionary.

这适用于我目前的用例:
extension CollectionType where Self: DictionaryLiteralConvertible,Self.Key: StringLiteralConvertible,Generator.Element == (Self.Key,Self.Value) { ... }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读