๐ŸŽ“ A1Learner
๐Ÿ”

Swift Array Methods

Array methods are built-in actions that change an array or build a changed copy of it. Some actions work on the stored array itself and some build a fresh array.

Adding to the end with append

The new value lands after the last stored value. The count grows by one with the addition.

var nums = [1, 2]
nums.append(3)
print(nums)
print(nums.count)

Placing a value with insert

The index in the call names the slot the new value takes. Values from that slot onward move one place along.

var nums = [1, 3, 4]
nums.insert(2, at: 1)
print(nums)

Taking a value out with remove

The index names the slot to clear. Later values slide back to fill the gap, and the count drops by one.

var nums = [1, 2, 3, 4]
nums.remove(at: 1)
print(nums)
print(nums.count)

Testing membership with contains

A stored value gives a true answer here. A value that was never stored gives a false answer.

var nums = [4, 8, 15]
print(nums.contains(8))
print(nums.contains(9))

A fresh sorted array versus sorting in place

The first print shows the fresh ordered copy. The second print shows the stored array still in its first order, and the third shows it after sorting in place.

var nums = [3, 1, 2]
print(nums.sorted())
print(nums)
nums.sort()
print(nums)

Example

var steps = [30, 10, 20]
steps.append(40)
print(steps)
print(Array(steps.reversed()))

Key points

  • Each method call runs one named action on the array it is attached to.
  • append adds one value to the end of an array.
  • insert(at:) adds one value at a chosen index.
  • remove(at:) takes out the value at a chosen index.
  • contains tells whether a value sits anywhere in the array.
  • sorted builds a fresh ordered array, and sort orders the stored array itself.

In this example, the first line stores three numbers in steps. The second line appends 40 to the end of the array. The third line prints the array as [30, 10, 20, 40]. The last line collects the values in reverse order into a plain array and prints [40, 20, 10, 30].

Note

Array(...) collects reversed values into a plain array that can print and store like any other array.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Swift Compiler

Exercise

An array holds [3, 1, 2]. A program prints the sorted copy and then prints the stored array. What does the stored array print?