Skip to content

Instantly share code, notes, and snippets.

@ilyapuchka
Created January 1, 2016 16:02
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 ilyapuchka/e511c7b49b29c4d46b85 to your computer and use it in GitHub Desktop.
Save ilyapuchka/e511c7b49b29c4d46b85 to your computer and use it in GitHub Desktop.
Conveniently access next element in collection
extension CollectionType where Index: Comparable {
subscript(safe index: Index) -> Generator.Element? {
guard index >= startIndex && index < endIndex else {
return nil
}
return self[index]
}
}
extension CollectionType where Generator.Element: Equatable, Index: Comparable {
subscript(next element: Generator.Element) -> Generator.Element? {
guard let index = self.indexOf(element) else { return nil }
return self[safe: index.advancedBy(1)]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment