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

I am trying to insert a new item at a specific place in the array using todo.insert and its not working, what am i doing

I am trying to insert a new item at a specific place in the array using todo.insert and its not working, what am i doing wrong.

In playground this works. todo.insert("Learn iOS", atIndex: 1)

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

todo.removeAtIndex(1)

let item = todo.removeAtIndex(1)

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

3 Answers

Hi Jordan, let me try to explain.

First of all, you deleted both "Build app" and "Deploy app" by writing this

todo.removeAtIndex(1)

let item = todo.removeAtIndex(1)

and you need to delete only "Deploy app".

Second, you are trying to append at index which can't be done, we use .insert for that. Like this:

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

This is correct

var todo = ["Learn Swift", "Build App", "Deploy App"]
todo += ["Debug App", "Fix Bugs"]
let item = todo.removeAtIndex(2)

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

Dang. I was going about it in a more complicated way than necessary. So close. Thank you so much, Petar!

Such a newb. :/

You're welcome, I am glad I helped.

And don't be discouraged. Keep learning and keep practicing, that is the only way to become good at programing. And even then you will not have all answers and you'll need to search for a solution on google or ask other people for help.

That is programing :)