swift - Collection 和 MutableCollection 上的扩展发生冲突并被 Xcode 声明为冗余

标签 swift swift4

我有一个文件,其中有 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/

相关文章:

ios - swift - 如何从服务器获取 JSON 响应

sprite-kit - 影响子节点的父节点的 Swift 4 SpriteKit : How to prevent the . alpha 属性?

swift - iOS Swift 图表显示 X 轴错误

objective-c - Objective-C 中的@testable 类比

ios - 如何使用 xcassets 构建框架

swift - 在 Swift 中,如何在对象创建后立即调用函数

swift - 将多个调用链接到同一方法时出现编译器问题

ios - 如何比较 WKNavigation 对象

swift - 当 uitableviewcell 被点击时,序列到 viewcontroller 并用所选单元格中的文本快速填充 uitextfield

swift - 如何根据键对字典进行排序并在 Swift 中对其各自的值进行排序