1

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?

1
  • 1
    firstArray.append(totalArray[i]) Commented Jan 16, 2023 at 17:48

2 Answers 2

3

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...])
Sign up to request clarification or add additional context in comments.

1 Comment

I am on my mobile but OP it is using <= not <
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.