在Swift数组中找到第一个元素匹配条件(例如EKSource)

时间:2015-11-19 05:07:23

标签: ios swift swift2 ios9 eventkit

我想在Swift中找到第一个EKSource类型为EKSourceType.Local的“单一”行表达式。这是我现在拥有的:

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

有没有更好的方法(例如没有映射和/或通用版本的find)?

7 个答案:

答案 0 :(得分:80)

或者在Swift3中你可以使用:

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

答案 1 :(得分:37)

indexOf的版本采用谓词闭包 - 用它来查找第一个本地源的索引(如果存在),然后在eventStore.sources上使用该索引:

if let index = eventStore.sources.indexOf({ $0.sourceType == .Local }) {
    let eventSourceForLocal = eventStore.sources[index]
}

或者,您可以通过find上的扩展程序添加通用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 })

(为什么不存在这个?)

答案 2 :(得分:19)

我不明白你为什么要使用map。为什么不使用filter?然后你会得到所有本地资源,但实际上可能只有一个,或者没有,你可以通过询问第一个来找到答案(如果没有&那将是nil 39; t one):

let local = eventStore.sources.filter{$0.sourceType == .Local}.first

答案 3 :(得分:10)

Swift 4 解决方案,当数组中没有符合您条件的元素时,它也会处理这种情况:

if let firstMatch = yourArray.first{$0.id == lookupId} {
  print("found it: \(firstMatch)")
} else {
  print("nothing found :(")
}

答案 4 :(得分:2)

让我们尝试更实用的功能:

let arr = [0,1,2,3]
let result = arr.lazy.map{print("");return $0}.first(where: {$0 == 2})
print(result)//3x  then 2

关于这个很酷吗?
您可以在搜索时访问元素或i。而且功能齐全。

答案 5 :(得分:2)

迅速5 如果要从模型数组中查找,请指定 $ 0.keyTofound ,否则使用 $ 0

if let index = listArray.firstIndex(where: { $0.id == lookupId }) {
     print("Found at \(index)")
} else {
     print("Not found")
 }

答案 6 :(得分:1)

对于Swift 3,您需要对Nate上面的答案做一些小改动。这是Swift 3版本:

settings.json

更改: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 } } > SequenceTypeSequence> Self.Generator.Element