Find first element matching condition in Swift array (e.g. EKSource)

Drux picture Drux · Nov 19, 2015 · Viewed 36.9k times · Source

I would like to find the first EKSource of type EKSourceType.Local with a "single"-line expression in Swift. Here is what I currently have:

let eventSourceForLocal = 
    eventStore.sources[eventStore.sources.map({ $0.sourceType })
        .indexOf(EKSourceType.Local)!]

Is there a better way of doing this (such as without mapping and/or with a generic version of find)?

Answer

Bueno picture Bueno · Jan 13, 2017

Alternatively in Swift3 you could use:

let local = eventStore.sources.first(where: {$0.sourceType == .Local})