In Swift, arrays are implemented as structs, making them value types rather than reference types (i.e., classes). When a value type is assigned to a variable as an argument to a function or method, a copy is created and assigned or passed.
Let’s take a look at an example of an Array
1 |
let starks: [String] = ["Eddard", "Catelyn", "Robb", "Sansa"] |
Here we have a basic Array, which is of type [String].
The square brackets indicate that this is an array of String objects, rather than just being a single String. As usual, Swift can infer this type data too, just by examining the initial assignment:
1 |
let starks = ["Robb", "Sansa", "Arya", "Jon"] |
We can access elements of this array in a variety of ways, such as using an Int index, calling the various collections methods.
1 |
let starks = ["Robb", "Sansa", "Arya", "Jon"] |
print( starks[0] )
print( starks[2] )
print( starks.first! ) //if starks.first is optional and has a value, unwrap optional and expose the value
Robb
Arya
Robb
Searching for item in array
not found returns nil
found returns the index
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
let array1 = ["a", "b", "c"] let array1Copy = array1.map{$0.copy()} let result = array1Copy.index (where: { (item) -> Bool in let temp = item as? String print ("comparing Array element: \(item), to (z)") if temp == "z" { print("we found!") return true } else { return false } }) print(result) |
If you try to access an index in an array that is not present, your program will fail at runtime! So always check the length of arrays when accessing by index:
1 2 3 |
if starks.count >= 4 { print( starks[3] ) } |
Accessing a non-existing element will crash
1 2 |
var myArray : [String] = [String]() //default constructor let a = myArray[0] // CRASH! |