我有一个包含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个单元格的表格.
我以前需要这个,并实现(我想说的是)一个非常好的解决方案.CycleSequence将任何一种形式包裹Collection在一个新的inifite中Sequence,它会释放出那些元素,永远循环.然后,您可以使用以下第一个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"))))
Run Code Online (Sandbox Code Playgroud)
输出:
[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")]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
92 次 |
| 最近记录: |