Iterate over collection two at a time in Swift

前端 未结 7 878
花落未央
花落未央 2020-11-28 16:00

Say I have an array [1, 2, 3, 4, 5]. How can I iterate two at a time?

Iteration 1: (1, 2)
Iteration 2: (3, 4)
Iteration 3: (5, nil)
7条回答
  •  有刺的猬
    2020-11-28 16:36

    One approach would be to encapsulate the array in a class. The return values for getting pairs of items would be optionals to protect against out-of-range calls.

    Example:

    class Pairs {
    
        let source = [1, 2, 3, 4, 5]  // Or set with init()
        var offset = 0
    
        func nextpair() -> (Int?, Int?) {
            var first: Int? = nil
            var second: Int? = nil
            if offset < source.count {
                first = source[offset]
                offset++
            }
            if offset < source.count {
                second = source[offset]
                offset++
            }
            return (first, second)
        }
    
    }
    

提交回复
热议问题