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

Michael Draper
Michael Draper
2,045 Points

Stuck on inserting an item into an array

I must be missing something here.

I'm trying to insert the new item in between "Learn Swift" and " Build app" and I must have the values incorrect. If "Learn Swift" is = 0 and "Build app" is = 1 and I'm trying to insert an item between the two, wouldn't the new item be 1? Thus, bumping "Build app" to 2?

Thanks!

arrays.swift
var todo = ["Learn Swift", "Build App", "Deploy App", "Debug App", "Fix Bugs"]
todo.removeAtIndex(1)
let item = todo.removeAtIndex(1)
todo.insert("Learn iOS", atIndex:1)
Kyle Lambert
Kyle Lambert
1,969 Points
Hi Michael I hope this helps a bit. You cant insert an "Learn iOS" between "Learn Swift" and
"Build App" because you already removed at index 1... Meaning you already removed "Build App"

You're second line of code is not needed and is the reason you're getting an error.

Task 1:
var todo = ["Learn Swift", "Build App", "Deploy App"]
todo += ["Debug App", "Fix Bugs"]

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

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

3 Answers

Michael Draper
Michael Draper
2,045 Points

I appreciate you taking the time! I did pass the quiz with your help! Although I must be hung up on some basic principle here. After adding the 2 additional strings from Task One to the array, their values are as follows, correct?

"Learn Swift" = 0 "Build App" = 1 "Deploy App" = 2 "Debug App" = 3 "Fix Bugs" = 4

If that is so, then when I enter:

todo.removeAtIndex(2)

I'd be removing "Deploy App" rather than "Build App", correct?

Kyle Lambert
Kyle Lambert
1,969 Points

Absolutely correct Michael. In task 2 you are asked to remove the item "Deploy App". Which is at index (2). Thus the line of code.

todo.removeAtIndex(2)

Appending items to an array will always add them to the end of the Array, therefore the index numbers will not change for the items already inside the Array. Index numbers will only change when removing or inserting items. You can use the count method to count the number of items inside your Array.

todo.count
Michael Draper
Michael Draper
2,045 Points

You.Are.Wonderful.

Thank you for your help.