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

b hartman
b hartman
323 Points

Why wouldn't this work the same? let item = "Test" todo.insert(newElement: item, atIndex: 2)

Challenge Task 2 of 3 for Collections: 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")
let item = "Test"
todo.insert(newElement: item, atIndex: 2)

Why wouldn't this work?

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

2 Answers

Stone Preston
Stone Preston
42,016 Points

the task states: Please remove the third item ("Deploy App") and assign it to a constant named item.

according to the documentation, swift arrays have a method called removeAtIndex:

removeAtIndex(_:)

Removes the element at the given index and returns it.

so we can remove the item and assign that item that was removed to a constant in one step:

var todo = ["Learn Swift", "Build App", "Deploy App"]
todo.append("Debug App")
todo.append("Fix Bugs")
let item = todo.removeAtIndex(2)
b hartman
b hartman
323 Points

Oh I see so when u remove it saves that item at once.

Cool thanks