无法使用类型为((Int,Int)'的参数列表调用'swapAt'

时间:2019-03-03 14:56:40

标签: swift

请考虑以下内容:

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个整数值。

enter image description here

2 个答案:

答案 0 :(得分:1)

实际上,没有,MutableCollection.swapAt没有定义为取两个# for each row in array2, check full match with each row in array1 bools = [np.all(array1==row,axis=1) for row in array2] # combine 3 boolean arrays with 'or' logic mask = [any(tup) for tup in zip(*bools)] # flip the mask mask = ~np.array(mask) # final index out = array1[mask] ,而是根据Int中的Index定义的:

MutableCollection

因此,除非添加,否则不能只使用swapAt(Self.Index, Self.Index)

Int

约束您的声明,使其:

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) } } } } 的迭代:

0 ..< count

答案 1 :(得分:1)

该屏幕截图是swapAt的{​​{1}}而不是Array的截图。与数组不同,集合可能具有非整数index(如String)。

您可以通过以下方式使用MutableCollection

Self.Index

或者根据 Sulthan Leo Dabus 的评论中的建议:

extension MutableCollection where Self:BidirectionalCollection, Element: Equatable {
    mutating func moveRight(_ value: Element){
        for i in (0..<self.count) {
            if self[index(startIndex, offsetBy: i)] == value {
                swapAt(startIndex, index(startIndex, offsetBy: 5))
            }
        }
    }
}