Skip to content

Instantly share code, notes, and snippets.

@natecook1000
Created September 20, 2018 22:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save natecook1000/27a757e77d19ecdb35a896a89a6749e1 to your computer and use it in GitHub Desktop.
Save natecook1000/27a757e77d19ecdb35a896a89a6749e1 to your computer and use it in GitHub Desktop.
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", ...)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment