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 Inserting and Deleting Values

I was doing the code challenge and I forgot how to RETRIEVE an item out of an array. Any tips or hints?

T&* $%E IU< T

2 Answers

David Papandrew
David Papandrew
8,386 Points

Hi JR,

To retrieve an array item, type the index position of the item you want enclosed in square brackets. Add this notation to the end of the object name. This is called a "subscript" and the Apple Documentation has more on the topic.

Here is example code:

let myArray = [1, 2, 3, 4, 5, 6]
//This returns the Int 5 since index starts at 0.
//So if you type myArray[0] you will get 1 from the Array
//You will use similar subscript for dictionaries and other collection types
SivaKumar Kataru
SivaKumar Kataru
2,386 Points

Retrieve or Reading an array is very simple.

// Creating a new array
var unitedStates: [String] = ["California","Ohio","Texas","North Carolina"] 

       ->  Reading an element from an array.
       ->  To read an element from an array we will be using subscript notation
              i.e followed by the name of an array and square brackets with index number or 
              position number of reading an element placed inside the square brackets 
              Example :   myList[5].
      ->     Let's say If you want to read an Nth element , say 2nd element to read,
              the index value is (n-1) = 2 - 1 = 1 .
      ->     Remember index of an array always starts with 0 

unitedStates[1] //  prints OHIO

// Assigning an array to constant or variable
var thirdElement = unitedStates[2]