Swift Introduction | Arrays and Dictionaries | Working with Array Elements

In the past, an array could not grow or shrink after its number of elements was set at creation time. Swift arrays, however, can be modified later by using array methods.

Methods? Yes, an array is also an object. You can process it by using its properties and methods. You can also combine arrays with the addition operator.

Combine arrays

variable = array + array

Append a value to the end of an array

array.append(value)

Insert a value at a specified position

array.insert(value, atIndex: insertionPosition)

Remove the last element

array.removeLast()

Remove the value at a specified index

array.removeAtIndex(index)

Remove values in a specified range

array.removeRange(range)

Remove all elements

array.removeAll()

Get the current number of elements

variable:Int = array.count

Get the first or last element

variable = array.first
variable = array.last

For insert, specify an integer position with atIndex. Use 0 to insert before the first element, 1 to insert between the elements at indexes 0 and 1, and so on.

For removeRange, specify the range by using the indexes of the elements to remove. For example, removeRange(3 ... 5) removes the elements at indexes 3 through 5.

Once you are comfortable with these methods and properties, you can work with arrays much more freely.