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?
In Swift it's really easy, use first(where method of the array. Like so:
first(where
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.
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
In Swift it's really easy, use
first(wheremethod of the array. Like so:Or, extended version:
The first and second piece of the code does the same thing.