5

假设我有这个 CGFloat 扩展

extension CGFloat {
    // common 
    public var thrice: CGFloat { return self * 3.0 }
    public var twice: CGFloat { return self * 2.0 }
    public var half: CGFloat { return self * 0.5 }
    public var third: CGFloat { return self / 3.0 }
    public var fourth: CGFloat { return self * 0.25 }
    public var sixth: CGFloat { return self / 6.0 }
    public var eighth: CGFloat { return self * 0.125 }
    public var twelfth: CGFloat { return self / 12.0 }
    public var sixteenth: CGFloat { return self * 0.0625 }

    //
    public var inverse: CGFloat { return 1.0 / self }
}

我想做的是让这些适用于 CGFloat、Double 和 Float,而无需复制/粘贴代码。这是可能吗?

谢谢!

4

1 回答 1

9

您不能通过扩展类型(一次全部)来做到这一点,但您可以使用模板函数来做到这一点:

protocol FloatLiteralMultipliable: FloatLiteralConvertible {
    func *(lhs: Self, rhs: Self) -> Self
    func /(lhs: Self, rhs: Self) -> Self
}

extension Float: FloatLiteralMultipliable {}
extension CGFloat: FloatLiteralMultipliable {}
extension Double: FloatLiteralMultipliable {}

func thrice<T: FloatLiteralMultipliable>(value: T) -> T { return value * 3.0 }
func twice<T: FloatLiteralMultipliable>(value: T) -> T { return value * 2.0 }
func half<T: FloatLiteralMultipliable>(value: T) -> T { return value / 2.0 }
func third<T: FloatLiteralMultipliable>(value: T) -> T { return value / 3.0 }
func fourth<T: FloatLiteralMultipliable>(value: T) -> T { return value / 4.0 }
func sixth<T: FloatLiteralMultipliable>(value: T) -> T { return value / 6.0 }
func eighth<T: FloatLiteralMultipliable>(value: T) -> T { return value * 0.125 }
func twelfth<T: FloatLiteralMultipliable>(value: T) -> T { return value / 12.0 }
func sixteenth<T: FloatLiteralMultipliable>(value: T) -> T { return value / 0.0625 }

func inverse<T: FloatLiteralMultipliable>(value: T) -> T { return 1.0 / value }

thrice(Float(10.0)) // 30.0
half(CGFloat(2)) // 1.0
inverse(Double(1.0/10.0)) // 10.0

注意:我只是在示例调用中显式构造类型,以证明函数可以与每种类型一起使用

于 2014-07-26T03:35:17.537 回答