请考虑以下内容:
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
定义的的 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
通过索引迭代:
for i in indices {
if (self[i] == value) {
// do swap
...
}
}
关于swift - 无法使用类型为 'swapAt' 的参数列表调用 '(Int, Int)',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54970140/