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
)?
I don't understand why you're using
map
at all. Why not usefilter
? You will then end up with all the local sources, but in actual fact there will probably be only one, or none, and you can readily find out by asking for the first one (it will benil
if there isn't one):Swift 4 solution that also handles the situation when there are no elements in your array that match your condition:
Alternatively in Swift3 you could use:
Let's try something more functional:
There's a version of
indexOf
that takes a predicate closure - use it to find the index of the first local source (if it exists), and then use that index oneventStore.sources
:Alternately, you could add a generic
find
method via an extension onSequenceType
:(Why isn't this there already?)
For Swift 3 you'll need to make a few small changes to Nate's answer above. Here's the Swift 3 version:
Changes:
SequenceType
>Sequence
,Self.Generator.Element
>Iterator.Element