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

标签 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

最佳答案

实际上没有,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/

相关文章:

swift - 如何在 Swift 中多态地转换为类类型?

ios - JSQMessagesViewController 点击消息 Action

iphone - 结束日期显示错误

swift - Nil不能赋值给类型()->()?

uitableview - Swift:没有名为的成员

ios - 突然出现“iPhone应用程序中的UIApplicationDelegate从未调用过reply()”错误

swift - 如何反复更新 UILabel 并控制其变化速度?

ios - SideMenu by jonkykong - 从右侧滑入

javascript - 将字典值中的整数分配给字符串的字符

ios - 单击按钮时如何防止查看 View (Swift)