我有一个文件,其中有 2 个不同的扩展名:
extension MutableCollection where Indices.Iterator.Element == Index { }
extension Collection where Indices.Iterator.Element == Index {}
在可变类中,我只有可变的扩展(有意义!对吧?),而在 Collection 中,我有两个类共有的扩展。
问题是我从 Swift 编译器收到这个警告:
Redundant same-type constraint 'Self.Index' == 'Self.Indices.Iterator.Element'
我应该怎么做才能修复它?
最佳答案
问题不在于你的两个扩展冲突,你会得到 具有单个扩展名的相同警告
extension Collection where Indices.Iterator.Element == Index { }
简短的回答是:只需从您的声明中删除多余的约束:
extension MutableCollection { ... }
extension Collection { ... }
说明: Swift 3 不允许约束关联
类型。即使满足 Indices.Iterator.Element == Index
对于所有具体集合(Array、ArraySlice、Set、...),
语言无法要求它。这就是为什么你必须添加
如果你需要的话,这个限制对你的扩展。
Swift 4 现在允许使用 where
约束关联类型
条款,参见 SE-0142 Permit where clauses to constrain associated types .
Collection
协议(protocol)定义
associatedtype Indices : Sequence = DefaultIndices<Self>
where Self.Index == Self.Indices.Element, ...
Sequence
协议(protocol)定义
associatedtype Element where Self.Element == Self.Iterator.Element
所以我们总是有身份
Indices.Iterator.Element == Indices.Element == Index
因此您可以从代码中移除这些约束。
关于swift - Collection 和 MutableCollection 上的扩展发生冲突并被 Xcode 声明为冗余,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46482160/