用自定义运算符覆盖类型转换 [英] Override typecasting with custom operators
本文介绍了用自定义运算符覆盖类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有这样的事情:
var x: Int = 6
var y: Float = 11.5
结果必须写成这样
so, the result has to be written like this
var result = Float(x) * y
或
var result = x * Int(y)
这很有道理,对吧?然而,我认为这有点笨拙,所以我想为此做一些自定义操作符:
This makes sense, right ?
However, I think that a little clumsy, so I'm trying to make some custom operators for this:
infix operator *~ { associativity left precedence 150 } //floating
func *~ (lhs: Float, rhs: Int) -> Float {
return lhs * Float(rhs)
}
func *~ (lhs: Int, rhs: Float) -> Float {
return rhs * Float(lhs)
}
infix operator *| { associativity left precedence 150 } //Integer
func *| (lhs: Float, rhs: Int) -> Int {
return Int(lhs) * rhs
}
func *| (lhs: Int, rhs: Float) -> Int {
return Int(rhs) * lhs
}
其中有太多,所以我试图为这些功能做一个通用版本。我到目前为止的尝试:
It works but there are too many of them, so I'm trying to make a generic version for these functions. My attempt so far:
func *~ <T: FloatingPointType, V:IntegerType>(lhs: T, rhs: V) -> T {
return lhs * T(rhs)
// error:
// Could not find an overload for 'init' that accepts the supplied arguments
}
有人可以帮忙吗?谢谢。
Can somebody help please ? Thank you.
推荐答案
protocol Fraction {
init(_ value: Double)
var asDouble: Double { get }
}
extension Int : Fraction { var asDouble : Double { return Double(self) } }
extension Double : Fraction { var asDouble : Double { return self } }
extension Float : Fraction { var asDouble : Double { return Double(self) } }
extension CGFloat : Fraction { var asDouble : Double { return Double(self) } }
infix operator ** { associativity left precedence 170 }
func **(lhs:Int, rhs:Int) -> Int {
return lhs * rhs
}
func **<T:Fraction, U:Fraction>(lhs:T, rhs:U) -> Double {
return lhs.asDouble * rhs.asDouble
}
2 ** 2 // 4
2 ** 2.2 // 4.4
2.5 ** 2 // 5.0
2.2 ** 2.2 // 4.84
这篇关于用自定义运算符覆盖类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文