比如说,我有一个数组 let array = [ "foo", "bar", "baz", "foobar", "qux"]
和这个数组中的索引 3。我想按以下顺序迭代数组中的所有元素 foobar
(索引 3 处的元素)、qux
(索引 4 处)、foo
(在索引 0 处等)、bar
、baz
。
不太优雅的解决方案看起来像这样:
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]
}
有没有更优雅的解决方案?
最佳答案
扩展和 %
运算符应该可以工作:
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"]
关于arrays - 按给定索引开始的顺序遍历数组中的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33013114/