Search code examples
swiftfoundation

Swift 3 Extend Range of Specific Type


Having trouble grasping what the syntax would be for extending a Range of a specific type/types. For example, if I only wanted to extend Range<Double> or Range<Int> or both.


Solution

  • You can't directly. It's a currently missing feature of Swift. You can get around it by using a dummy protocol:

    protocol _Int {}
    extension Int: _Int {}
    
    extension CountableClosedRange where Bound: _Int {
        var sum: Int {
            // These forced casts are acceptable because
            // we know `Int` is the only type to conform to`_Int`
            let lowerBound = self.lowerBound as! Int
            let upperBound = self.upperBound as! Int
            let count = self.count as! Int
    
            return (lowerBound * count + upperBound * count) / 2
        }
    }
    
    print((1...100).sum) //5050
    

    The FloatingPoint or Integer protocols may also be useful here.