Skip to content

Instantly share code, notes, and snippets.

@erica erica/doihatethis.swift
Last active Oct 30, 2015

Embed
What would you like to do?
//: 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
You can’t perform that action at this time.