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

Martin Z
PLUS
Martin Z
Courses Plus Student 755 Points

How to remove a particular item in an array?

I am having rouble dealing with one of the challenges I received after watching the video "Modifying an Array". It asks me to remove one of the items in the array and assign it to a constant named "item". I tried the methods in the video but they didn't work out for what reason I don't know. Someone helps me please?

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

2 Answers

In order to remove an item in an array, first you must know the name of the item you wish to remove along with it's respective position (or index) within the array. I believe the challenge asks you to remove the item "Deploy App", which is in the third position within the array. This means it's index is 2. To do this you would write:

 todo.removeAtIndex(2)

To assign it to a constant named "item", you simply do:

let item = todo.removeAtIndex(2)
Martin Z
Martin Z
Courses Plus Student 755 Points

First of all, thank you very much for answering my question. But I found it doesn't work using your method and I checked it for several minutes and I realized that if I removed the item of "Deploy App" then the item which has and index of 2 will be "Debug App". So after typing the second line in, the system gave me a Bummer! The solution I came up with is just by typing in the second line you suggested me and it actually worked.

Martin- I never meant to suggest that the answer is both of these lines of code. I simply provided the first line to represent a step in the problem solving process- to explain the syntax for removing an item at a certain position.

let item = todo.removeAtIndex(2)

Is the complete constant declaration and assignment to the first explanatory line of code I provided, and the full answer. Sorry for the confusion!

Martin Z
PLUS
Martin Z
Courses Plus Student 755 Points

Oh that was my misunderstanding... I am new to coding! Thank you for your detailed answer and patience!

No problem. Keep up the good work!