Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


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.

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

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.