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

Kim Mathiasen
Kim Mathiasen
922 Points

Swift Basics Task 2 of 3 changing arrays why do I get an error when removing at index 2?

When trying the following code, I get the error: 'item' should have the value "Deploy App" but has the value "Debug App". It works if I change the index to 1...

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

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

todo.removeAtIndex(2) let item = todo.removeAtIndex(2)

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

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

todo.removeAtIndex(2)
let item = todo.removeAtIndex(2)

3 Answers

Hi Kim,

Looks like your code is removing the item at index 2 twice over, and assigning to a variable the second time. And that final assigned value is "Debug App".

All you have to is remove one specific line of code, and it'll work! :)

Hope this helps,

Ajay

Kim Mathiasen
Kim Mathiasen
922 Points

Hi Ajay, Thanks a lot - that worked perfectly! So, here's a newbie question: Even after having removed one line of code, does that mean that the entry "Deploy App" is still deleted from the array or is it just added to the constant 'item'? It seems that two operations is performed in the same line...

Kim

I haven't actually worked with Swift specifically, but I found this in the language reference:

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html#//apple_ref/doc/uid/TP40014097-CH8-ID105

You're quite right: that one line in your code does both the removal of the item from the array, and assigns it to the item variable. By design, the removeAtIndex method returns the item being removed - useful if (as in this code challenge) you want to capture and use it for something else.

Ajay

Kim Mathiasen
Kim Mathiasen
922 Points

Great - thanks for your help Ajay!

No wuzzers Kim!