Line At A Time
Lesson 14: Indexes and count
Indexes and count Pick single items out of an array.
1let fruits = ["apple", "banana", "cherry"]
2print(fruits[0])
3print(fruits.count)
Terminal
$ swift main.swift
apple
3
Every line, explained
let fruits = ["apple", "banana", "cherry"]
An array stores several values in one variable. The values go between square brackets, separated by commas.
print(fruits[0])
You get one item using its index (position) in square brackets, and counting starts at 0, not 1! fruits[0] is "apple", fruits[1] is "banana", fruits[2] is "cherry".
print(fruits.count)
.count tells you how many items the array holds: here, 3. (Swift says count, where some languages say length or len.)