在Swift数组中找到第一个元素匹配条件(例如EKSource) [英] Find first element matching condition in Swift array (e.g. EKSource)
问题描述
我想找到第一个 EKSource
类型 EKSourceType.Local
带有单一线表达式在斯威夫特。这是我目前所拥有的:
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
)?
推荐答案
有一个 indexOf
的版本采用谓词闭包 - 用它来查找第一个本地源的索引(如果存在),以及然后在 eventStore.sources上使用该索引
:
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 on eventStore.sources
:
if let index = eventStore.sources.indexOf({ $0.sourceType == .Local }) {
let eventSourceForLocal = eventStore.sources[index]
}
或者,您可以通过 SequenceType $上的扩展名添加通用
find
方法c $ c>:
Alternately, you could add a generic find
method via an extension on SequenceType
:
extension SequenceType {
func find(@noescape predicate: (Self.Generator.Element) throws -> Bool) rethrows -> Self.Generator.Element? {
for element in self {
if try predicate(element) {
return element
}
}
return nil
}
}
let eventSourceForLocal = eventStore.sources.find({ $0.sourceType == .Local })
(为什么不存在?)
这篇关于在Swift数组中找到第一个元素匹配条件(例如EKSource)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!