Skip to content

Instantly share code, notes, and snippets.

@erica
Last active October 30, 2015 03:46
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 erica/cbfa6ed6f85283f4c087 to your computer and use it in GitHub Desktop.
Save erica/cbfa6ed6f85283f4c087 to your computer and use it in GitHub Desktop.
//: 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