How can I find an item of a specific type in an array

88 views Asked by At

How can I find an item of a specific type in an array?

For example: I have an array of pets.

let pets: [Animal] = [Cat(), Cat(), Fish(), Dog()]

How do I find the first item of type Dog?

2

There are 2 answers

2
Fahri Azimov On BEST ANSWER

In Swift it's really easy, use first(where method of the array. Like so:

let cat = pets.first { $0 is Cat }

Or, extended version:

let cat = pets.first { (animal) -> Bool in
    return animal is Cat
}

The first and second piece of the code does the same thing.

0
timbre timbre On

A more generic version, and the function looks like this:

func findAnimal<T: Animal>(ofType: T.Type) -> Animal? {

    return pets.first {
        guard let t = $0 as? T else {
            return false
        }
        return type(of: t) == ofType
    }
}

For example:

findAnimal(ofType: Dog.self)

will return a dog from the array