Skip to content

Instantly share code, notes, and snippets.

@slazyk
Last active August 29, 2015 14:03
Show Gist options
  • Save slazyk/80b317663f5866cee290 to your computer and use it in GitHub Desktop.
Save slazyk/80b317663f5866cee290 to your computer and use it in GitHub Desktop.
Ranges in Swift
// <a..b> <a..b| |a..b> |a..b|
operator prefix | { }
operator postfix | { }
operator prefix < { }
operator postfix > { }
enum Bound<T: ForwardIndex> {
case Closed (@auto_closure () -> T)
case Open (@auto_closure () -> T)
}
@prefix func | <T: ForwardIndex> (x: T) -> Bound<T> { return .Open (x) }
@postfix func | <T: ForwardIndex> (x: T) -> Bound<T> { return .Open (x) }
@prefix func < <T: ForwardIndex> (x: T) -> Bound<T> { return .Closed (x) }
@postfix func > <T: ForwardIndex> (x: T) -> Bound<T> { return .Closed (x) }
@infix func .. <T: ForwardIndex> (f: Bound<T>, t: Bound<T>) -> Range<T> {
switch (f, t) {
case (.Closed (let x), .Closed (let y)): return x()...y()
case (.Closed (let x), .Open (let y)): return x()..<y()
case (.Open (let x), .Closed (let y)): return x().successor()...y()
case (.Open (let x), .Open (let y)): return x().successor()..<y()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment