重复遍历一个小数组以获得更多的项目

时间:2019-02-19 23:01:40

标签: arrays swift

我有5个对象的数组。但是我想对其进行迭代,以便最终得到100个对象。一旦到达数组索引的末尾,如何返回0并开始直到100次迭代?

假设我的数组是["a", "b", "c", "d", "e"],那么我想要的结果是:

  

0 = a 1 = b 2 = c 3 = d 4 = e 5 = a 6 = b 7 = c 8 = d 9 = e 10 = a

以此类推。

我想通过重复此列表中的项目来填充100个单元格的表格。

3 个答案:

答案 0 :(得分:6)

我以前需要这个,并且实现了(我要说的)一个很好的解决方案。 CycleSequence将任何类型的Collection包装到一个新的inifite Sequence中,该inifite发出那些元素,并永远循环。然后,您可以使用n来获取前.prefix(n)个元素:

struct CycleSequence<C: Collection>: Sequence {
    let cycledElements: C

    init(cycling cycledElements: C) {
        self.cycledElements = cycledElements
    }

    public func makeIterator() -> CycleIterator<C> {
        return CycleIterator(cycling: cycledElements)
    }
}

struct CycleIterator<C: Collection>: IteratorProtocol {
    let cycledElements: C
    var cycledElementIterator: C.Iterator

    init(cycling cycledElements: C) {
        self.cycledElements = cycledElements
        self.cycledElementIterator = cycledElements.makeIterator()
    }

    public mutating func next() -> C.Iterator.Element? {
        if let next = cycledElementIterator.next() {
            return next
        } else {
            self.cycledElementIterator = cycledElements.makeIterator() // Cycle back again
            return cycledElementIterator.next()
        }
    }
}

print(Array(CycleSequence(cycling: [true, false]).prefix(7)))
print(Array(CycleSequence(cycling: 1...3).prefix(7)))
print(Array(CycleSequence(cycling: "ABC").prefix(7)))
print(Array(CycleSequence(cycling: EmptyCollection<Int>()).prefix(7)))
print(Array(zip(1...10, CycleSequence(cycling: "ABC"))))

输出:

[true, false, true, false, true, false, true]
[1, 2, 3, 1, 2, 3, 1]
["A", "B", "C", "A", "B", "C", "A"]
[]
[(1, "A"), (2, "B"), (3, "C"), (4, "A"), (5, "B"), (6, "C"), (7, "A"), (8, "B"), (9, "C"), (10, "A")]

答案 1 :(得分:4)

模运算符%将在这里成为您的朋友。 我面前没有编译器,总是弄乱范围语法,但是下面应该说明这个想法……

for i in 0..<100 {
    let theItem = array[i % array.count]
}

答案 2 :(得分:0)

有一个外部for循环迭代100次,有一个内部forEach循环遍历数组。

let array = [Int]()

for index in 0..<100 {
    array.forEach { element in
        print(element)
    }
}

简而言之:迭代一百次。

相关问题