Swift: search array by id

The find function in swift only supports finding equality (==) elements. I want to search for an element by id (===). For example. with this setup:

class A {}

let first = A()
let last = A()
let absent = A()
let array = [first, last]

      

I want to be able to do something like:

find(array, first) // -> 0
find(array, last) // -> 1
find(array, absent) // -> nil

      

Does anyone have a correct way to make it fast?

+2


source to share


1 answer


I couldn't find a built-in library function, but this should work:

func findIdenticalObject<T : AnyObject>(array: [T], value: T) -> Int? {
    for (index, elem) in enumerate(array) {
        if elem === value {
            return index
        }
    }
    return nil
}

      



The identity operator ===

is only defined for instances of classes, so the generic function is only defined for <T : AnyObject>

.

+2


source







All Articles