ios - 按索引移动数组中的元素

标签 ios arrays swift generics

给定 n 个元素的数组,即

var 数组 = [1, 2, 3, 4, 5]

我可以为 Array 编写一个扩展,这样我就可以修改数组来实现此输出:[2, 3, 4, 5, 1]:

mutating func shiftRight() {
  append(removeFirst())
}

有没有办法实现这样一个函数,可以按任何索引(正数或负数)移动数组。我可以使用 if-else 子句以命令式方式实现此函数,但我正在寻找的是函数式实现。

算法很简单:

  1. 根据提供的索引将数组分成两部分
  2. 将第一个数组附加到第二个数组的末尾

有没有办法以函数式的方式实现它?

我完成的代码:

extension Array {
  mutating func shift(var amount: Int) {
    guard -count...count ~= amount else { return }
    if amount < 0 { amount += count }
    self = Array(self[amount ..< count] + self[0 ..< amount])
  }
}

最佳答案

您可以使用范围下标并连接结果。这将为您提供您正在寻找的内容,其名称类似于标准库:

extension Array {
    func shiftRight(var amount: Int = 1) -> [Element] {
        guard count > 0 else { return self }
        assert(-count...count ~= amount, "Shift amount out of bounds")
        if amount < 0 { amount += count }  // this needs to be >= 0
        return Array(self[amount ..< count] + self[0 ..< amount])
    }

    mutating func shiftRightInPlace(amount: Int = 1) {
        self = shiftRight(amount)
    }
}

Array(1...10).shiftRight()
// [2, 3, 4, 5, 6, 7, 8, 9, 10, 1]
Array(1...10).shiftRight(7)
// [8, 9, 10, 1, 2, 3, 4, 5, 6, 7]

您还可以从 shiftRight() 返回 Array(suffix(count - amount) + prefix(amount)),而不是下标。

关于ios - 按索引移动数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39751122/

相关文章:

ios - 如何在 View Controller 中多次加载相同的 View

IOS-Facebook 应用授权后空白屏幕

ios - JSON 未在 TableView 中加载

ios - 就像谷歌有操作系统版本/设备的官方统计数据一样,苹果有使用 ios5/4.x 的 % 设备的统计数据吗?

c - 获取数组索引的问题 [C]

ios - 为什么打印语句没有按正确的顺序执行??我疯了还是Xcode?

ios - 应用因 UITabBarController 和应用内购买而崩溃

C++ 求数组中数字的平均值

c - 一道新手C题

swift - 如何声明以函数为值并以整数为键的字典?