-2

I have an array of, for example 10 elements:

var Ar = [0,1,2,3,4,5,6,7,8,9]

And I need to make new array from current array by taken each second element for example -

var newAr = [1,3,5,7,9]

How can I do it in Swift?

2
  • 2
    Hi tePoloN, welcome to the site. This isn't a free code-writing service. We're here to help with concrete issues in real code. Show us what you tried and where you got stuck, and we can help from there. Commented Aug 19, 2021 at 16:00
  • Exactly! Thank you! Commented Aug 19, 2021 at 16:10

1 Answer 1

1

You can loop over all the indices, and if an odd number, append it to a result array.

Example:

let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var result = [Int]()

for index in arr.indices {
    if !index.isMultiple(of: 2) {
        result.append(arr[index])
    }
}

print(result)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.