Coding for All
Lesson 15: Growing Arrays
Growing Arrays Add to an array with append.
1var fruits = ["apple", "banana"]
2fruits.append("cherry")
3print(fruits)
Terminal
$ swift main.swift
["apple", "banana", "cherry"]
Every line, explained
var fruits = ["apple", "banana"]
var creates a variable: a box whose value CAN change. The Swift rule of thumb: use let unless you truly need to change the value. (Swift even warns you if a var never actually changes!) This array must be a var: an array made with let is locked, and Swift will refuse to append to it. We plan to change it, so var it is.
fruits.append("cherry")
.append(...) adds a new item to the END of the array. The array grows from 2 items to 3.
print(fruits)
print(...) shows whatever is inside its round brackets in the terminal, then moves to a new line. All lowercase, both brackets needed, and no semicolon at the end; Swift doesn't use them. The cherry is now in the array.