Skip to content

Instantly share code, notes, and snippets.

@airspeedswift
Created June 27, 2015 21:42
Show Gist options
  • Save airspeedswift/8cd05040558da5a91362 to your computer and use it in GitHub Desktop.
Save airspeedswift/8cd05040558da5a91362 to your computer and use it in GitHub Desktop.
Anything can be Sliceable
public struct SubSliceView<C: CollectionType>: Sliceable {
let collection: C
let bounds: Range<C.Index>
public var startIndex: C.Index { return bounds.startIndex }
public var endIndex: C.Index { return bounds.endIndex }
public subscript(idx: C.Index) -> C.Generator.Element
{ return collection[idx] }
typealias SubSlice = SubSliceView<C>
public subscript(bounds: Range<C.Index>) -> SubSliceView<C> {
return SubSliceView(collection: collection, bounds: bounds)
}
}
extension AnyRandomAccessCollection: Sliceable {
public subscript(bounds: Range<Index>) -> SubSliceView<AnyRandomAccessCollection> {
return SubSliceView(collection: self, bounds: bounds)
}
}
let a = [1,2,3]
let r = AnyRandomAccessCollection(a)
print("")
print(dropFirst(dropFirst(r)).first)
// now in theory this ought to work? but compiler is segfaulting...
//extension CollectionType {
// public subscript(bounds: Range<Index>) -> SubSliceView<Self> {
// return SubSliceView(collection: self, bounds: bounds)
// }
//}
//
// then all you'd need to do is tag each collection
//extension UnsafeBufferPointer: Sliceable { }
//extension Dictionary: Sliceable { }
//extension AnyRandomAccessIndex: Sliceable { }
// or maybe some day extension CollectionType: Sliceable { }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment