Last active
October 30, 2015 03:46
-
-
Save erica/cbfa6ed6f85283f4c087 to your computer and use it in GitHub Desktop.
This file contains 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
//: Playground - noun: a place where people can play | |
import UIKit | |
// Test data | |
let x = ["a", "b", "c", "d", "e"] | |
let y = "Hello world" | |
/* | |
Unsafe index manipulation: can return invalid results | |
since the index is manipulated without regard to the | |
underlying instance | |
*/ | |
func +<Index: ForwardIndexType>(idx: Index, distance: Index.Distance) -> Index { | |
return idx.advancedBy(distance) | |
} | |
func -<Index: BidirectionalIndexType>(idx: Index, distance: Index.Distance) -> Index { | |
return idx.advancedBy(-distance) | |
} | |
/* | |
Safer indexing, takes end index into account for forward indexing | |
and start index for backwards indexing | |
*/ | |
infix operator -->> {} | |
func -->><C:CollectionType where C.Index: BidirectionalIndexType> (collection: C, distance: C.Index.Distance) -> C.Index { | |
return collection.startIndex.advancedBy(distance, limit: collection.endIndex.predecessor()) | |
} | |
infix operator ->> {} | |
func ->><C:CollectionType where C.Index: BidirectionalIndexType> (collection: C, distance: C.Index.Distance) -> C.Generator.Element { | |
return collection[collection -->> distance] | |
} | |
infix operator <<-- {} | |
func <<--<C:CollectionType where C.Index: BidirectionalIndexType> (collection: C, distance: C.Index.Distance) -> C.Index { | |
return collection.endIndex.predecessor().advancedBy(-distance, limit: collection.startIndex) | |
} | |
infix operator <<- {} | |
func <<-<C:CollectionType where C.Index: BidirectionalIndexType> (collection: C, distance: C.Index.Distance) -> C.Generator.Element { | |
return collection[collection <<-- distance] | |
} | |
// e.g. | |
y.substringFromIndex(y.startIndex + 3) | |
y.substringToIndex(y.endIndex - 3) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment