Created
September 20, 2018 22:35
-
-
Save natecook1000/27a757e77d19ecdb35a896a89a6749e1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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