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 trialNika 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,830 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,830 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
14,575 PointsJhoan Arango
14,575 PointsThere are different methods on doing this.. but as a quick answer. Yes