How can I interleave two arrays?

前端 未结 4 1200
予麋鹿
予麋鹿 2020-11-29 12:20

If I have two arrays e.g

let one = [1,3,5]
let two = [2,4,6]

I would like to merge/interleave the arrays in the following pattern [one[0],

4条回答
  •  攒了一身酷
    2020-11-29 12:56

    With Swift 5, you can use one of the following Playground sample codes in order to solve your problem.


    #1. Using zip(_:_:) function and Collection's flatMap(_:) method

    let one = [1, 3, 5, 7]
    let two = [2, 4, 6]
    
    let array = zip(one, two).flatMap({ [$0, $1] })
    print(array) // print: [1, 2, 3, 4, 5, 6]
    

    Apple states:

    If the two sequences passed to zip(_:_:) are different lengths, the resulting sequence is the same length as the shorter sequence.


    #2. Using an object that conforms to Sequence and IteratorProtocol protocols

    struct InterleavedSequence: Sequence, IteratorProtocol {
    
        private let firstArray: [T]
        private let secondArray: [T]
        private let thresholdIndex: Int
        private var index = 0
        private var toggle = false
    
        init(firstArray: [T], secondArray: [T]) {
            self.firstArray = firstArray
            self.secondArray = secondArray
            self.thresholdIndex = Swift.min(firstArray.endIndex, secondArray.endIndex)
        }
    
        mutating func next() -> T? {
            guard index < thresholdIndex else { return nil }
            defer {
                if toggle {
                    index += 1
                }
                toggle.toggle()
            }
            return !toggle ? firstArray[index] : secondArray[index]
        }
    
    }
    
    let one = [1, 3, 5, 7]
    let two = [2, 4, 6]
    
    let sequence = InterleavedSequence(firstArray: one, secondArray: two)
    let array = Array(sequence)
    print(array) // print: [1, 2, 3, 4, 5, 6]
    

提交回复
热议问题