Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Can I replace Indexes in Swift array?

can I replace Indexes in array? For example:

var todo = [ "Finish collection course", "Buy groceries", "Response to emails", "Order book online" "Pay bills" ]

If I want to move [0] on place of [2] and index [4] on place of index [1].

I dont know if I’ll ever need it but just curious.

Jhoan Arango
Jhoan Arango
14,575 Points

There are different methods on doing this.. but as a quick answer. Yes

3 Answers

Here's one way:

var todo = [ "Finish collection course", "Buy groceries", "Response to emails", "Order book online", "Pay bills" ]

let temp = todo.removeAtIndex(0)  //take out the one you want to move
todo.insert(temp, atIndex: 1)  //insert it where you want it to go
print(todo)

The print output is:

["Buy groceries", "Finish collection course", "Response to emails", "Order book online", "Pay bills"]

Note: there's a comma missing between the last two elements of your array in the code you pasted in above.

Thanks. That's what I thought but I Wanted to know if there is some other easier (handy) way than "todo.removeAtIndex" and then "todo.insert"

Actually, there is, but you need to use inout parameters:

swap(&todo[0], &todo[1])

Great, that makes sense :) Thank you.