Learn
Now that we have an array, how do we retrieve an individual value? This is where index comes into play.
An index refers to an item’s position within an ordered list. Arrays in Swift are zero-indexed, meaning the first item has index 0, the second index 1, and so on.
For example, suppose we have a String
array with all the vowels:
var vowels = ["a", "e", "i", "o", "u"]
- The item at index 0 is
"a"
. - The item at index 1 is
"e"
. - The item at index 2 is
"i"
. - The item at index 3 is
"o"
. - The item at index 4 is
"u"
.
To retrieve individual elements, we can use the subscript syntax, array[index]
. The subscript syntax uses square brackets, [
]
, around an index value.
For example:
print(vowels[0]) // Prints: a print(vowels[1]) // Prints: e print(vowels[2]) // Prints: i print(vowels[3]) // Prints: o print(vowels[4]) // Prints: u
Instructions
1.
The 24-hour weather forecast is recorded in an array called temperature
, starting with the current temperature as its first value.
Print the current temperature using its index.
Take this course for free
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.