gpt4 book ai didi

Swift 3 扩展特定类型的范围

转载 作者:搜寻专家 更新时间:2023-11-01 06:36:47 24 4
gpt4 key购买 nike

无法理解扩展 Range 的语法是什么特定类型/类型。例如,如果我只想扩展 Range<Double>Range<Int>或两者兼而有之。

最佳答案

你不能直接。这是 Swift 目前缺少的功能。您可以使用虚拟协议(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

FloatingPointInteger 协议(protocol)在这里也很有用。

关于Swift 3 扩展特定类型的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40580054/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com