Arrays
- use to organize a list of variables, constants, and other types
- all items must be of the same type (Ints, Floats, Strings, objects, optionals)
- items are indexed by integers starting with zero
- if copied → Pass by Value (original array is unchanged)
Performance Notes
- as an array grows in size, its capacity is doubled at certain breakpoints – 2, 4, 8, 16…
- when capacity is doubled, the array is reallocated in memory which can be an intensive process for a large array
- use
reserveCapacity
method to help control memory usage
Declaration
// declaration only, cannot append
var array1: [String]
// declaration - create/init with 0 value
var array2 = [Int]()
var array25: [Int] = []
// create and initialize with an initial value (preferred)
var array3 = ["A", "B", "C"]
// declare and populate with repeated values
var array4 = Array(repeating:"Zebra", count:3)
// creating from a dictionary (can use values also)
let dict0 = [1: "first", 2: "second"]
var array5 = Array(dict0.keys)
- if
let
is used → array is immutable (cannot change/add to it)
- when creating from a dictionary, the array order is random
Retrieval
// -> Zebra
let animal = array4[2]
// -> A, B, C
print(array3)
Add Items append += insert
- adds to the end of the list (except
insert
)
// add 1 item -> 2
array2.append(2)
// add multiple items -> 2, 4, 5
array2.append(contentsOf: [4, 5])
// add a range of Ints -> 2, 4, 5, 1, 2...
array2.append(contentsOf: 1...6)
print(array2)
// shorthand method (+/=)
// adds multiple -> A, B, C, D, E
array3 += ["D", "E"]
// concatenate 2 arrays (index #'s continue after 1st array)
// -> Kiwi, Pears, Kiwi, Pears
array3 += array3
// clears except for item -> Pears
array3 = ["Pears"]
// add at a specific point (insert) -> Kiwi, Pears
array3.insert("Kiwi", at: 0)
Remove Items
// all index #'s shift down -> returns 2
array2.remove(at: 0)
// -> returns 6
array2.removeLast()
// removes all, but array stays initialized
array2.removeAll(keepingCapacity: true)
array2 = []
Change Items
- reference the item index with
[]
and assign a new value
// overwrites -> .1 = Peaches
array3[1] = "Peaches"
// adds via concatenation -> .1 = Peaches and cream
array3[1] += " and cream"
// overwrites multiple -> Zebra, Fox, Mice
array4[1...2] = ["Fox", "Mice"]
Iterating over Array Items
// -> Zebra, Bands, Straws
for i in array3 {
print("i = \(i)")
}
// -> Fruit: Kiwi at: 0...
for index in 0 ..< array3.count {
print("Fruit: \(array3[index]) at: \(index)")
}
// naming both -> Fruit: Kiwi at: 0...
for (index, fruit) in array3.enumerated() {
print("Fruit: \(fruit) at: \(index)")
}
i index fruit
→ auto declared type-inferred constants used to iterate so that the item evaluated is not altered
enumerated()
→ returns a tuple composed of – index and item value
Multiple Type Arrays
- not recommended, but possible
// -> Array<any>.Type
var songs: [Any] = ["Rose", "Bud", 3]
type(of: songs)
</any>
Miscellaneous Functions
// count the # of items -> 0
array2.count
// returns a Bool (true = empty) -> true
array2.isEmpty
// shows if the array contains a certain value (true = yes)
array3.contains("Bandanas")
// assigning value to first|last items
// -> Kiwi
let firstFruit = array3.first
// -> Peaches and cream
let lastFruit = array3.last
Arrays pass by value
var arrayA = [1, 2, 3]
var arrayB = arrayA
arrayB[0] = 10
// -> 1, 2, 3
arrayA
// -> 10, 2, 3
arrayB