Finding the index/indices of an element in an array

Swift 3, macOS 10.12

class Food {
var name: String = ""

init(name: String){
self.name = name
}
}

let chocolate = Food(name: "Chocolate")
let spinach = Food(name: "Spinach")
let greenTea = Food(name: "Green Tea")

let favouriteThings = [greenTea, chocolate, greenTea, spinach, greenTea]

If your element conforms to the equatable protocol or inherits from NSObject, you have the index(of:) method of Array available:

let indexOfSpinach = favouriteThings.index(of: spinach) //Optional(3)

If it doesn’t, as in the example above, where Food is a Swift class that doesn’t inherit from anything or conform to anything, you’re out of luck and the method does not show up in code completion, if you try to use it anyway, you’ll get Cannot invoke ‘index’ with an argument type ‘(of: Food)’

However, you can use a closure to check the identity of an object:
let indexOfSpinach = favouriteThings.index(where: {$0 === spinach }) //Optional(3)

So let’s get to my favouritest food in the whole wide world: Green Tea.
let indexOfGreenTea = favouriteThings.index(where: {$0 === greenTea} )// Optional(0)

So the first time greenTea is in my array is favouriteThings[0], but what about the others?

We need a variable to store out indices:
var indices: [Int] = []

In order to get the indices of all elements, we use an enumerator:

for (index, element) in favouriteThings.enumerated() {
if element === greenTea {
indices.append(index)
}
}

print(indices)

This does not work with structs because the identify operator === does not make sense with structs; in order to work with equality, you’d need to make your struct equatable, which, since this was only a moment of curiousity, I shall not do at this point.