Skip to content

Instantly share code, notes, and snippets.

@natecook1000
Created September 20, 2018 22:35
Show Gist options
  • Save natecook1000/27a757e77d19ecdb35a896a89a6749e1 to your computer and use it in GitHub Desktop.
Save natecook1000/27a757e77d19ecdb35a896a89a6749e1 to your computer and use it in GitHub Desktop.

Revisions

  1. natecook1000 created this gist Sep 20, 2018.
    26 changes: 26 additions & 0 deletions firstLiteralMatch.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    extension Collection where Element: Hashable {
    /// Returns the first matching element in `needles`, along with its index.
    func firstLiteralMatch<C: Collection>(from needles: C) -> (C.Element, Index)?
    where C.Element: Collection, C.Element.Element == Element
    {
    let prefixes = Dictionary(grouping: needles, by: { $0.first! })
    for i in indices {
    if let possibleMatches = prefixes[self[i]] {
    if let match = possibleMatches.first(where: { self[i...].starts(with: $0) }) {
    return (match, i)
    }
    }
    }
    return nil
    }
    }

    let text = """
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. \
    Nullam a imperdiet magna. Quisque quis libero non risus \
    commodo efficitur. Sed lorem urna, scelerisque sit \
    amet porta eget, efficitur at libero. Ut a viverra augue.
    """

    text.firstLiteralMatch(from: ["sit", "elit", "libero"])
    // ("sit", ...)