请考虑以下事项:
extension MutableCollection where Self:BidirectionalCollection, Element: Equatable {
mutating func moveRight(_ value: Element){
for i in (0..<self.count) {
if (self[self.index(self.startIndex, offsetBy: i)] == value){
swapAt(0, 5)
}
}
}
}
Xcode显示
swapAt(0,5)
处的错误。为什么?swapAt
是需要2个整数(索引)的方法,我提供2个整数值。最佳答案
实际上不,MutableCollection.swapAt没有定义为取两个,它是根据Int
的Index
定义的:
swapAt(Self.Index, Self.Index)
因此,除非添加
Index == Int
限制您的声明,使其:
extension MutableCollection where Self: BidirectionalCollection, Element: Equatable, Index == Int {
mutating func moveRight(_ value: Element){
for i in (0..<self.count) {
if (self[self.index(self.startIndex, offsetBy: i)] == value){
swapAt(0, 5)
}
}
}
}
如果不想将自己限制为整数索引,则应首先将
MutableCollection
中的迭代替换为索引上的迭代:for i in indices {
if (self[i] == value) {
// do swap
...
}
}