Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 3扩展特定类型的范围_Swift_Foundation - Fatal编程技术网

Swift 3扩展特定类型的范围

Swift 3扩展特定类型的范围,swift,foundation,Swift,Foundation,无法理解扩展特定类型的范围的语法。例如,如果我只想扩展范围或范围或两者兼而有之。您不能直接扩展。这是Swift目前缺失的一项功能。您可以使用虚拟协议绕过它: protocol _Int {} extension Int: _Int {} extension CountableClosedRange where Bound: _Int { var sum: Int { // These forced casts are acceptable because

无法理解扩展特定类型的
范围的语法。例如,如果我只想扩展
范围
范围
或两者兼而有之。

您不能直接扩展。这是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

浮点
整数
协议在这里也可能有用。

您不能直接使用。这是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

FloatingPoint
Integer
协议在这里也可能有用。

我遇到了类似的问题,但其他解决方案不起作用。确实如此

extension CountableClosedRange where Bound: Integer, Bound == Int {
...
} 
只是使用

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

在编码(代码完成)方面工作良好,但在编译过程中导致了分段错误11。

我也有类似的问题,但其他解决方案不起作用。确实如此

extension CountableClosedRange where Bound: Integer, Bound == Int {
...
} 
只是使用

extension CountableClosedRange where Bound == Int {
...
}
在编码(代码完成)方面工作良好,但在编译期间导致分段错误11