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