Skip to content

Instantly share code, notes, and snippets.

@Pretz
Created September 24, 2015 18:21
Show Gist options
  • Save Pretz/23057802003f1f4936a7 to your computer and use it in GitHub Desktop.
Save Pretz/23057802003f1f4936a7 to your computer and use it in GitHub Desktop.
Fetch items from a Swift collection using negative indices
import Swift
extension CollectionType where Index: SignedNumberType, Index == Index.Distance {
func get(var position: Self.Index) -> Self.Generator.Element? {
if position < 0 {
position = self.endIndex.advancedBy(position)
}
return (indices ~= position) ? self[position] : nil
}
}
let a = [1, 2, 3, 4, 5]
a.get(-2) // returns 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment