Array

Array is an ordered, random-access collection type. Arrays are one of the most commonly used data types in an app. We use the Array type to hold elements of a single type, the array’s Element type. An array can store any kind.

Empty arrays

The following three declarations are equivalent:

// A mutable array of Strings, initially empty.

var arrayOfStrings: [String] = [] 

var arrayOfStrings = [String]() 

var arrayOfStrings = Array<String>()

Multi-dimensional arrays

A multidimensional array is created by nesting arrays.

2D Array

let twoDArray = [[Int]] or Array<Array<Int>>

3D Array

let threeDArray: [[[Int]]]

Modifying an Array

  1. Appending Elements
var numbers = [1, 2, 3] 

numbers.append(4) // [1, 2, 3, 4]
  1. Inserting Elements
numbers.insert(0, at: 0) // [0, 1, 2, 3, 4]
  1. Removing Elements
numbers.remove(at: 1) // Removes the second element (1) 
numbers.removeLast() // Removes the last element 
numbers.removeAll() // Empties the array
  1. Updating Elements
numbers[0] = 100 // Changes the first element to 100

Iterating Through an Array

  1. For Loop
for number in numbers { 
print(number) 
}
  1. For Loop with Index
for (index, value) in numbers.enumerated() { 
print("Index \(index): \(value)") 
}

Leave a Reply

Your email address will not be published. Required fields are marked *