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 Build a Simple iPhone App with Swift Creating a Data Model Creating a Data Collection

Challenge 2/2 Creating a Data Collection

I have no clue how to do this challenge. Please help!!

The challenge: We are at the grocery store and we picked up the bread. Using array subscripting, retrieve the string "bread" from the array and assign it to a variable named cart.

The only code I have is from the first part of this challenge, which is:

var shoppingList: [String] = ["toothpaste", "bread", "eggs"]

5 Answers

Since "bread" is the second element, it would be something like this:

var cart = shoppingList[1]

Chris Shaw
Chris Shaw
26,676 Points

Hi Shelby,

The challenge task is asking you to select the second value or bread in this case, to get this value we simply need to select the index for the value bread and assign it back to a variable called cart.

Remember that arrays always start at index 0, i.e

let types: [String] = ["String", "Boolean", "Double", "Int"]
let myType: String = types[1] // results in "Boolean"

Hope that helps.

So how would you assign it the variable "cart"?

Chris Shaw
Chris Shaw
26,676 Points

Hi Shelby,

I would urge you to go back and watch the variables video linked below as this has been covered off many times already throughout the course.

http://teamtreehouse.com/library/swift-basics/variables-and-constants/variables

Andrew Brotherton
Andrew Brotherton
7,515 Points

This is from the documentation provided by Apple: Retrieve a value from the array by using subscript syntax, passing the index of the value you want to retrieve within square brackets immediately after the name of the array:

var firstItem = shoppingList[0] // firstItem is equal to "Eggs" This is what you need to do to retrieve the item from the array. The next question asks you to assign it to a variable called cart.

judah simon
judah simon
4,886 Points

The challenge: We are at the grocery store and we picked up the bread. Using array subscripting, retrieve the string "bread" from the array =shoppingList[1] because it is the second item and assign it to a variable named cart. =var cart therefore var cart =shoppingList[1]

Maher Alhasan
Maher Alhasan
974 Points

var cart = shoppingList[1]