TL ; DR:
insert(x, at: i) puts x at index i. Use remove(at: i) to take out the item at index i. The other items move to make room or to close the gap.
var colors = ["red", "green", "blue"]
colors.insert("pink", at: 1)
print(colors) // ["red", "pink", "green", "blue"]
colors.remove(at: 0)
print(colors) // ["pink", "green", "blue"]
Full lesson:
append adds an item at the end. To put one anywhere else in an array, use insert(x, at: i). The items from index i on move one place to the right.
var pets = ["Rex", "Milo"]
pets.insert("Luna", at: 0)
print(pets) // ["Luna", "Rex", "Milo"]
You met remove(at:) in the last lesson. It takes out the item at index i. The items after it move one place to the left. It also returns the item:
let first = pets.remove(at: 0)
print(first) // Luna
print(pets) // ["Rex", "Milo"]
Watch the indexes. After an insert or a removal, the items behind that spot have new indexes.
Note the order in insert. The value comes before the index.
Your task
pets holds the pets waiting at the vet, in order.
Bella has an appointment, so she goes second, at index 1. Then Milo goes home. Take him out of the line.
The code below prints how many pets wait once Bella is in. At the end, it prints the pets left.
Expected output:
4
Rex Bella LunaFree plan: 30 tutor messages. PRO is unlimited.
