Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,520 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,520 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.