【发布时间】:2016-12-15 06:11:21
【问题描述】:
我正在(为一篇文章)实现两个自定义中缀运算符:
- ¿% - 计算总数的百分比。
- %? - 计算代表总数的百分比。
在调试了一些错误并查找信息后,我终于找到了让我的代码正常工作的方法:
protocol NumericType {
static func *(lhs: Self, rhs: Self) -> Self
static func *(lhs: Self, rhs: Int) -> Self
static func /(lhs: Self, rhs: Self) -> Self
static func /(lhs: Self, rhs: Int) -> Self
} // NumericType
extension Double : NumericType {
internal static func *(lhs: Double, rhs: Int) -> Double {
return lhs * Double(rhs)
}
internal static func /(lhs: Double, rhs: Int) -> Double {
return lhs / Double(rhs)
}
}
extension Float : NumericType {
internal static func *(lhs: Float, rhs: Int) -> Float {
return lhs * Float(rhs)
}
internal static func /(lhs: Float, rhs: Int) -> Float {
return lhs / Float(rhs)
}
}
extension Int : NumericType { }
infix operator ¿%
func ¿% <T: NumericType>(percentage: T, ofThisTotalValue: T) -> T {
return (percentage * ofThisTotalValue) / 100
} // infix operator ¿%
infix operator %?
func %? <T: NumericType>(segmentOf: T, thisTotalValue: T) -> T {
return (segmentOf * 100) / thisTotalValue
} // infix operator %?
let percentage: Double = 8
let price: Double = 45
let save = percentage ¿% price
print("\(percentage) % of \(price) $ = \(save) $")
print("\(save) $ of \(price) $ = \(save %? price) %")
...输出:
8.0 % of 45.0 $ = 3.6 $
3.6 $ of 45.0 $ = 8.0 %
我的问题如下:
您认为还有更优化和更易读的方法吗?
是吗?您能给出一些建议或分享一个例子吗?
【问题讨论】:
-
您的代码似乎按预期工作。如果您正在寻找可能改进的评论和建议,请将其发布到 codereview.stackexchange.com。
-
我会的,谢谢你的建议。