迭代数组中的所有元素,以便开始给定索引

时间:2015-10-08 10:26:38

标签: arrays swift

说,我在这个数组中有一个数组let array = [ "foo", "bar", "baz", "foobar", "qux" ]和一个索引3。我想按以下顺序迭代数组中的所有元素foobar(索引3处的元素),qux(索引4处),foo(索引0处等), barbaz

不那么优雅的解决方案看起来像这样:

for index in givenIndex ..< array.endIndex {
  // do some work with array[index]
}

for index in array.startIndex ..< givenIndex {
  // do the same work with array[index]
}

有更优雅的解决方案吗?

2 个答案:

答案 0 :(得分:3)

扩展名和%运算符应该有效:

extension CollectionType where Index : IntegerType, Index.Distance == Index {
  func offset(by: Index) -> [Generator.Element] {
    guard by >= 0 else { return offset(by+count) }
    return (by..<(by+count))
      .map { i in self[i % count + startIndex] }
  }
}


let array = [ "foo", "bar", "baz", "foobar", "qux" ]

array.offset( 1) // ["foobar", "qux", "foo", "bar", "baz"]
array.offset(-1) // ["qux", "foo", "bar", "baz", "foobar"]

let s = array.suffixFrom(2) // ["baz", "foobar", "qux"]

s.offset( 1) // ["foobar", "qux", "baz"]
s.offset(-1) // ["qux", "baz", "foobar"]

答案 1 :(得分:3)

为了避免重复工作块,您可以将范围转换为数组并添加它们:

let givenIndex = 3
let array = [ "foo", "bar", "baz", "foobar", "qux" ]

for index in Array(givenIndex ..< array.endIndex) + Array(0 ..< givenIndex) {
    // do some work with array[index]
    print(array[index])
}

替代答案

由于优雅是旁观者的眼睛,另一种避免重复工作块的方法是将你的范围放在一个数组中,然后在迭代之前按顺序选择它们:

for range in [givenIndex ..< array.endIndex, 0 ..< givenIndex] {
    for index in range {
        // do some work with array[index]
        print(array[index])
    }
}