Skip to content

Instantly share code, notes, and snippets.

@eonist
Created January 13, 2017 12:12
Show Gist options
  • Save eonist/8a2d07e72519ae0da6ee5f321e14c670 to your computer and use it in GitHub Desktop.
Save eonist/8a2d07e72519ae0da6ee5f321e14c670 to your computer and use it in GitHub Desktop.
Swift 3 Range Idea: One range type to rule them all πŸ‘‘
/*Assert methods*/
class RangeAsserter{
static func equals(_ a: IRange, _ b:IRange) -> Bool {
return a.start == b.start && a.end == b.end
}
}
/*Parser methods*/
class RangeParser{
static func length(_ range:IRange) -> Int {
return (range.end) - (range.start)
}
}
/**
* Serves as a common denominator for Range and CountableRange
* Apples motivation for seperating these types was:
* 1. Make a light-weight range type that only holds 2 Ints (start and end)
* 2. Make a heavy-weight range type that holds a copy of the original Collection type (aka Array)
* With IRange we create an universal API to access both types
*/
protocol IRange{
var end:Int {get }
var start:Int {get }
}
extension IRange{
var length:Int {return RangeParser.length(self)}
func equals(_ range:IRange)->Bool{return RangeAsserter.equals(self,range)}
}
/**
* We inject IRange functionality onto both Range types: Range and CountableRange
* So that Range and CountableRange can be treated the same way with out too much verbosity and complex syntactical sugar
*/
extension Range:IRange{
var start:Int {return self.lowerBound as! Int}
var end:Int {return self.upperBound as! Int}
}
extension CountableRange:IRange{
var start:Int {return self.lowerBound as! Int}
var end:Int {return self.upperBound as! Int}
}
/*testing*/
let countableRange:CountableRange<Int> = (0..<4)
countableRange.length//4
let range:Range = 2..<5
range.length//3
countableRange.equals(range)//false
(0..<4).equals(0..<4)//true
@eonist
Copy link
Author

eonist commented Jan 23, 2017

Nice idea but ultimately wasn't pursued.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment