代码之家  ›  专栏  ›  技术社区  ›  RyanTCB

逐字循环数组

  •  -2
  • RyanTCB  · 技术社区  · 7 年前

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

    0=A1=B2=C3=D4=E5=A6=B7=C8=D9=E10=a

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

    3 回复  |  直到 7 年前
        1
  •  7
  •   Alexander    7 年前

    CycleSequence Collection 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"))))
    

    输出:

    [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")]
    
        2
  •  4
  •   theMikeSwan    7 年前

    模算子 % 会是你在这里的朋友。 我没有一个编译器在我面前,总是搞砸范围语法,但下面应该说明这个想法

    for i in 0..<100 {
        let theItem = array[i % array.count]
    }
    
        3
  •  0
  •   Gustavo Vollbrecht    7 年前

    有外遇 for forEach 循环遍历数组。

    let array = [Int]()
    
    for index in 0..<100 {
        array.forEach { element in
            print(element)
        }
    }
    

    简而言之: 在迭代中迭代一百次。