Created
September 24, 2015 18:21
-
-
Save Pretz/23057802003f1f4936a7 to your computer and use it in GitHub Desktop.
Fetch items from a Swift collection using negative indices
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
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