请考虑以下事项:

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个整数值。
swift - 无法使用类型为((Int,Int)&#39;的参数列表调用&#39;swapAt&#39;-LMLPHP

最佳答案

实际上不,MutableCollection.swapAt没有定义为取两个,它是根据IntIndex定义的:

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
       ...
    }
}

10-06 13:11