Created
January 1, 2016 16:02
-
-
Save ilyapuchka/e511c7b49b29c4d46b85 to your computer and use it in GitHub Desktop.
Conveniently access next element in 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
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