The index(of:)
method returns Int?
, which means that if the object is not found in the array, the return value is nil, otherwise it is an Int.
Arrays work like this:
index 1
|
V
[locA, locB, locC]
^ ^
| |
index 0 index 2
If you call locations.index(of:locB)
the return value will be Optiona(1)
.
and every time it finds it increases index by 1?
Absolutely not! When the index(of:) method finds the object it stops and returns the index:
...
let loc1 = Location(1,2)
let loc2 = Location(3,4)
let loc3 = Location(5,6)
let loc4 = Location(7,8)
let locations = [loc3, loc2, loc3, loc3] //Note how many times loc3 is present in the array
if let index = locations.index(of: loc3) {
print(index)
}
else {
print("not found")
}
--output:--
0
From the docs:
func index(of: Element)
Returns the first index where the specified value appears in the collection.
looking for an annotation as! Location
element
The annotation variable, which is of type MKAnnotation, was assigned a Location object by iOS. But in order to compare the annotation variable to variables of type Location, like the ones in the locations
array, you have to cast the annotation variable to the type Location. Here is an example:
...
let loc1 = Location(1,2)
let loc2 = Location(3,4)
let loc3 = Location(5,6)
let loc4 = Location(7,8)
let locations = [loc3, loc2, loc3, loc3]
let annotation: MyAnnotation = loc3
if let index = locations.index(of: annotation) { //=> error: ... expected argument type Location
print(index)
}
else {
print("not found")
}
You cannot look for an MKAnnotation object in an array populated with Location objects. If the annotation variable was actually assigned a Location object (other classes could have implemented the MKAnnotation protocol and therefore could have been assigned to the annotation variable as well), then you can cast the annotation variable to type Location, then search for the object in the array.