Last active
December 28, 2018 23:21
-
-
Save dduan/5e531aaef4a47b51c0009cc3287b6952 to your computer and use it in GitHub Desktop.
Find first index of occurrence of a collection in a collection.
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
/// Usage: myString.firstIndex(of: otherString) | |
extension BidirectionalCollection where Element: Equatable { | |
func firstIndex(of other: Self) -> Index? { | |
guard | |
let start = other.first.flatMap(self.firstIndex(of:)), | |
self[start...].count >= other.count, | |
case let end = self.index(start, offsetBy: other.count), | |
zip(self[start ..< end], other).allSatisfy(==) | |
else | |
{ | |
return nil | |
} | |
return start | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment