简体   繁体   English

如何对 Swift 中的所有数字类型进行通用扩展?

[英]How can I make a generic extension on all number types in Swift?

I am adding a computed property in extensions for my personal use, but sometimes I need this functionality in all number type values, how can I stop myself of repeating codes?我在扩展中添加了一个计算属性供我个人使用,但有时我需要在所有数字类型值中使用此功能,我怎样才能阻止自己重复代码?

My goal is making just one extension for all number type.我的目标是只为所有号码类型制作一个扩展名。


extension CGFloat {
    
    var powered: CGFloat {
        get { return self * self }
    }
    
}


extension Double {
    
    var powered: Double {
        get { return self * self }
    }
    
}


extension Int {
    
    var powered: Int {
        get { return self * self }
    }
    
}

You can extend Numeric protoocol and return Self :您可以扩展Numeric协议并返回Self

extension Numeric {
    var powered: Self { self * self }
}

CGFloat(3).powered // CGFloat 9
2.powered          // Int 4
2.5.powered        // Double 6.25
Decimal(5).powered // Decimal 25

Note that this is possible because Numeric protocol requires that the types that conform to it to implement * and *= operator functions.请注意,这是可能的,因为Numeric协议要求符合它的类型来实现**=运算符函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM