Swift 3 扩展特定类型的范围

Swift 3 Extend Range of Specific Type

无法理解扩展特定 type/types 的 Range 的语法。例如,如果我只想扩展 Range<Double>Range<Int> 或两者。

你不能直接。这是 Swift 当前缺少的功能。您可以使用虚拟协议绕过它:

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

FloatingPointInteger 协议在这里也可能有用。

我遇到了类似的问题,但其他解决方案均无效。这确实

extension CountableClosedRange where Bound: Integer, Bound == Int {
...
} 

刚刚使用

extension CountableClosedRange where Bound == Int {
...
}

编码(代码完成)工作正常,但在编译期间导致分段错误 11。