I'm implementing (for an article) two custom infix operators:
¿%- to calculate percent of total%?- to calculate the percent that represents a segment of total
After debugging some errors and looking for information I finally found a way to get my code working:
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 Double : NumericType
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 Float : NumericType
extension Int : NumericType { }
infix operator ¿%
func ¿% <T: NumericType>(percentage: T, ofThisTotalValue: T) -> T {
return (percentage * ofThisTotalValue) / 100
} // infix operator ¿%
infix operator %?
func %? <T: NumericType>(segment: T, ofThisTotalValue: T) -> T {
return (segment * 100) / ofThisTotalValue
} // 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) %")
The output:
8.0 % of 45.0 $ = 3.6 $
3.6 $ of 45.0 $ = 8.0 %
Do you thinks there could be a more optimal and readable approach? Could you give some advice or share an example?