Iterate over collection two at a time in Swift

前端 未结 7 941
花落未央
花落未央 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:15

    I personally dislike looping through half the list (mainly because of dividing), so here is how I like to do it:

    let array = [1,2,3,4,5];
    var i = 0;
    
    while i < array.count {
        var a = array[i];
        var b : Int? = nil;
        if i + 1 < array.count {
            b = array[i+1];
        }
        print("(\(a), \(b))");
    
        i += 2;
    }
    

    You loop through the array by incrementing by 2.

    If you want to have nil in the element, you need to use optionals.

提交回复
热议问题