swift - 如何在 Bound 是通用的地方扩展 ClosedRange
问题描述
对于一些附加功能,我想扩展ClosedRange
Bounds 所在的位置Measurement
。
extension ClosedRange where Bound == Measurement
…显然不能Measurement
作为泛型类型需要<>
参数。
extension ClosedRange where Bound == Measurement<UnitType> // Cannot find type 'UnitType' in scope
连接where
s 似乎也不起作用。
我没主意了。
我发现唯一有效的是:
extension ClosedRange where Bound == Measurement<UnitLength> {
func unit() -> UnitLength {
return lowerBound.unit
}
}
let range = Measurement(value: 5, unit: UnitLength.meters)...Measurement(value: 15, unit: UnitLength.meters)
range.unit().symbol // m
但我不想为所有单位类型复制和粘贴它。毕竟这不就是泛型的用途吗?
这接近我想要的,但不起作用:
extension ClosedRange where Bound == Measurement<UnitType> { // Cannot find type 'UnitType' in scope
func unit() -> UnitType { // Cannot find type 'UnitType' in scope
return lowerBound.unit
}
}
let range = Measurement(value: 5, unit: UnitLength.meters)...Measurement(value: 15, unit: UnitLength.meters)
range.unit
编辑:
感谢 Dávid Pásztor 的回答。我想扩展我的问题:
如何为Measurement
s添加一个UnitType
继承自 s的函数Dimension
?
extension ClosedRange {
func convertedLowerBound<UnitType>(to unit: UnitType) -> Double where Bound == Measurement<UnitType> {
lowerBound.converted(to: unit).value // Referencing instance method 'converted(to:)' on 'Measurement' requires that 'UnitType' inherit from 'Dimension'
}
}
let range = Measurement(value: 5, unit: UnitLength.meters)...Measurement(value: 15, unit: UnitLength.meters)
range.convertedLowerBound(to: .centimeters)
Referencing instance method 'converted(to:)' on 'Measurement' requires that 'UnitType' inherit from 'Dimension'
是的,我可以打电话range.lowerBound.converted(to: .centimeters)
。我计划实现的确切功能不是这样工作的。
解决方案
您需要使扩展本身具有通用性,但是 Swift 尚不支持。不过,您可以使函数本身通用。
extension ClosedRange {
func unit<UnitType>() -> UnitType where Bound == Measurement<UnitType> {
lowerBound.unit
}
func convertedLowerBound<UnitType: Dimension>(to unit: UnitType) -> Double where Bound == Measurement<UnitType> {
lowerBound.converted(to: unit).value
}
}
推荐阅读
- laravel - 不是 laravel 5 db:seed 中的关系
- macos - 在 mac 上观看 videolectures.net
- javascript - 来自内部的角度访问功能,然后在承诺中
- angular - 如何在悬停时打开导航栏 ngbDropdown?
- docker - Windows Docker NAT 似乎完全崩溃了
- google-colaboratory - 使 colab 使用最新安装的库
- internet-explorer - Internet Explorer 中的多个 Select2 标记问题
- javascript - 访问用户集合中的数组。[Meteor + React Native]
- unity3d - Unity3D - 为什么以简单复制的方式重构我的脚本不起作用?
- javascript - 将 Array.push 作为参数传递会在 JavaScript 中引发异常