Finding an Element in Swift Collections
I repeatedly came across a small problem in my Swift code where I want to find the first element in a collection (e.g. an array) where a certain property equals a specific value. Here’s what I came up with.
extension Collection {
/// Find the first element where the value at `keyPath` is equal to `value`.
///
/// Example: `superheroes.first(where: \.name, equals: "Superman")`
func first<T: Equatable> (where keyPath: KeyPath<Element, T>, equals value: T)
-> Element?
{
first {
$0[keyPath: keyPath] == value
}
}
}