Swift: What's the best way to pair up elements of an Array

前端 未结 4 894
独厮守ぢ
独厮守ぢ 2020-11-30 10:42

I came across a problem that required iterating over an array in pairs. What\'s the best way to do this? Or, as an alternative, what\'s the best way of transforming an Array

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 10:54

    You can map the stride instead of iterating it, that allows to get the result as a constant:

    let input = [1, 2, 3, 4, 5, 6]
    
    let output = stride(from: 0, to: input.count - 1, by: 2).map {
        (input[$0], input[$0+1])
    }
    
    print(output) // [(1, 2), (3, 4), (5, 6)]
    

    If you only need to iterate over the pairs and the given array is large then it may be advantageous to avoid the creation of an intermediate array with a lazy mapping:

    for (left, right) in stride(from: 0, to: input.count - 1, by: 2)
        .lazy
        .map( { (input[$0], input[$0+1]) } ) {
    
        print(left, right)
    
    }
    

提交回复
热议问题