【问题标题】:Iterate over all elements in the array in order starting given index按给定索引开始的顺序遍历数组中的所有元素
【发布时间】:2015-10-08 21:31:00
【问题描述】:

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

不太优雅的解决方案如下所示:

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]
}

有没有更优雅的解决方案?

【问题讨论】:

    标签: arrays swift


    【解决方案1】:

    扩展和% 运算符应该可以工作:

    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"]
    

    【讨论】:

    • 没问题!不过,它确实需要稍作更改,以便与切片一起使用。
    【解决方案2】:

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

    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])
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-05
      • 2018-02-21
      • 1970-01-01
      • 1970-01-01
      • 2018-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多