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 Collections and Control Flow Introduction to Collections Working With Arrays

Clifton Blair
Clifton Blair
2,108 Points

Retrieve an item through subscript syntax.

How would I retrieve an item through subscript syntax?

array.swift
// Enter your code below
var arrayOfInts = [1,2,3,4,5,6]
arrayOfInts.append(7)
[1,2,3,4,5,6] + [7]
let value = arrayOfInts

1 Answer

andren
andren
28,558 Points

You would use square bracket like this:

arrayOfInts[0] // This retrieves the first item from the array.

It's important to note that array indexes are 0 based, meaning that they start at 0. The first item would therefore be [0], the second item [1] and so on.

Clifton Blair
Clifton Blair
2,108 Points

for some reason I am inputing let value = arrayOfInts[5]

but it is not accepting my answer.

andren
andren
28,558 Points

That would be because of array indexes being 0 based. As I mentioned in my post [0] is the first item, [1] is the second item and so on. This means that [5] actually refers to the sixth item in the array.

To retrieve the fifth item which is what the task asks you have to use [4]. 0-based lists are often confusing to people new to programming at first, but they are so common in programming that you will get used to them eventually.