Skip to content

Instantly share code, notes, and snippets.

@dduan
Last active December 28, 2018 23:21
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 dduan/5e531aaef4a47b51c0009cc3287b6952 to your computer and use it in GitHub Desktop.
Save dduan/5e531aaef4a47b51c0009cc3287b6952 to your computer and use it in GitHub Desktop.
Find first index of occurrence of a collection in a collection.
/// 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