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.

Nika Elashvili
5,201 PointsCan 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.
3 Answers

jcorum
71,814 PointsHere'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.

Nika Elashvili
5,201 PointsThanks. 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"

jcorum
71,814 PointsActually, there is, but you need to use inout parameters:
swap(&todo[0], &todo[1])

Nika Elashvili
5,201 PointsGreat, that makes sense :) Thank you.
Jhoan Arango
13,603 PointsJhoan Arango
13,603 PointsThere are different methods on doing this.. but as a quick answer. Yes