#26: Different Ways to Add Elements to an Array

Swift arrays have a few different insertion APIs depending on what you are adding and where it should go.

var values = [1, 2]
values.append(3)                 // [1, 2, 3]
values += [4, 5]                 // [1, 2, 3, 4, 5]
values.append(contentsOf: [6, 7])
values.insert(0, at: 0)          // [0, 1, 2, 3, 4, 5, 6, 7]

Use append for one element, append(contentsOf:) or += for multiple elements, and insert(_:at:) when position matters.

The more specific method usually makes the code easier to read.


I'm also on Twitter and GitHub.

Subscribe via RSS.