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

前端 未结 7 1698
迷失自我
迷失自我 2020-12-24 05:35

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:

7条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-24 06:26

    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]
    }
    

    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 })
    

    (Why isn't this there already?)

提交回复
热议问题