7 个解决方案
1、有一个版本的indexOf使用一个谓词闭包——使用它查找第一个本地源的索引(如果存在的话),然后在eventstore上使用该索引。
if let index = eventStore.sources.indexOf({ $0.sourceType == .Local }) {
let eventSourceForLocal = eventStore.sources[index]
}
2、扩展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 })
3、let local = eventStore.sources.first(where: {0.sourceType == .Local}.first
5、let arr = [0,1,2,3]
let result = arr.lazy.map{return 0 == 2})
6、public extension Sequence {
func find(predicate: (Iterator.Element) throws -> Bool) rethrows -> Iterator.Element? {
for element in self {
if try predicate(element) {
return element
}
}
return nil
}
}
7、if let firstMatch = yourArray.first(where: {$0.id == lookupId}) {
print("found it: (firstMatch)")
} else {
print("nothing found :(")
}
转自:https://www.itdaan.com/blog/2015/11/19/38d85f65e896aa6a557ec7c2574717ee.html