Skip to content

Instantly share code, notes, and snippets.

@hsavit1
Forked from alskipp/findFirst.swift
Created December 14, 2015 18:36
Show Gist options
  • Select an option

  • Save hsavit1/c464deac6eaa7321072d to your computer and use it in GitHub Desktop.

Select an option

Save hsavit1/c464deac6eaa7321072d to your computer and use it in GitHub Desktop.

Revisions

  1. @alskipp alskipp created this gist Oct 21, 2015.
    29 changes: 29 additions & 0 deletions findFirst.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,29 @@
    extension SequenceType {
    func find(predicate: Generator.Element -> Bool) -> Generator.Element? {
    for x in self {
    if predicate(x) { return x }
    }
    return .None
    }
    }

    infix operator <|> {}

    // Alternative for Optional - return `lhs` if non-nil, otherwise return `rhs`
    func <|> <A>(lhs:A?, rhs:A?) -> A? {
    return lhs.map { $0 } ?? rhs
    }

    // Find the first element in SequenceType argument that matches an element in `self`
    extension SequenceType where Generator.Element: Equatable {
    func findFirst<S:SequenceType where S.Generator.Element == Generator.Element>(xs: S) -> Generator.Element? {
    return xs.reduce(.None) { acc, x in
    acc <|> self.find { $0 == x }
    }
    }
    }

    // examples:
    [3,29,9,23].findFirst(20...30) // .Some(23)
    [3,29,9,23].findFirst([50, 9, 3]) // .Some(9)
    ["a","b","c"].findFirst(["x","b"]) // .Some("b")