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 Swift Basics (retired) Collections Modifying an Array

nulled
nulled
1,890 Points

Inserting a new item in an array but can't find the problem.

Asked to insert a new item titled "Learn iOS" at the second position of the todo array. While I think I wrote the code correctly, it states my 'todo' variable contains a wrong value.

var todo = ["Learn Swift", "Build App", "Deploy App"]

todo.append ("Debug App")

todo.append ("Fix Bugs")

todo.removeAtIndex(4)
let item = "Deploy App"

todo.insert ("Learn iOS", atIndex: 2)

Any help?

2 Answers

Tobias Mahnert
Tobias Mahnert
89,414 Points

Hey Bernadino,

the Code below passes the Challenge, also it's a bit optimized in order to be dry. if you want to know why, please let me know. Also mark my answer as best answer if it helped you.

Cheers toby

var todo = ["Learn Swift", "Build App", "Deploy App"]

todo += ["Debug App","Fix Bugs"] 

let item = todo.removeAtIndex(2)

todo.insert ("Learn iOS", atIndex: 1)
Martin Wildfeuer
PLUS
Martin Wildfeuer
Courses Plus Student 11,071 Points

Not bad, you managed to trick code check into letting you pass this assignment although it shouldn't have :)

Now that we have to fix bugs in our app we cannot deploy it. Please remove the third item ("Deploy App") and assign it to a constant named item.

var todo = ["Learn Swift", "Build App", "Deploy App"]
todo.append ("Debug App")
todo.append ("Fix Bugs")

todo.removeAtIndex(4)
let item = "Deploy App"

With todo.removeAtIndex(4), you are removing "Fix Bugs" instead of "Deploy App" from the todo array. With an array, indices are zero based, that is:

var todo = [(0) "Learn Swift",  (1) "Build App",  (2) "Deploy App", (3) "Debug App", (4) "Fix Bugs"]

In order to remove the third item, you would have to provide the index (2)

Moreover removeAtIndex(index: Int) returns the element that was removed. Code check did not notice that you were simply assigning this String manually again, whereas it should be:

let item = todo.removeAtIndex(2)

So, given what I said about indices above, this is also true for adding an item at an index. If you want something to be added as the second item, index has to be 1, as the first item has index 0.

todo.insert ("Learn iOS", atIndex: 1)

Hope that helps :)