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 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]
myArray[4]
//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"] 

/*
              //////////////////////////////////////////////////////////////////
                                          NOTES
            //////////////////////////////////////////////////////////////////
       ->  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]



          ```