Home > Back-end >  How to divide one array into two half arrays in swift
How to divide one array into two half arrays in swift

Time:01-17

I have one array. I need to divide that array into two halves; first half in one array, second in another.

tried code:

let totalArray = [20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10]

var firstArray = [Int]()
var secondArray = [Int]()

for i in totalArray.indices {
    if i <= totalArray.count/2 {
        firstArray.append(contentsOf: [i])
    } else {
        secondArray.append(contentsOf: [i])
    }
}

o/p:

[0, 1, 2, 3, 4, 5]
[6, 7, 8, 9, 10]

But I need it like this:

firstArray = [20, 19, 18, 17, 16, 15]
secondArray = [14, 13, 12, 11, 10]

What am I doing wrong?

CodePudding user response:

You are appending the indices rather than the values (see howaldoliverdev's answer).

But this is Swift. There are more convenient ways to split the array for example

let totalArray = [20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10]

let mid = (totalArray.count   1) / 2

let firstArray = Array(totalArray[..<mid])
let secondArray = Array(totalArray[mid...])

CodePudding user response:

contentsOf gives you the content of "i" itself, which carries the index number (the position of the array item), not the respective value of the array item.

You want:

firstArray.append(totalArray[i])

secondArray.append(totalArray[i])

That way, you get back the value from the array item at the respective position.

  • Related