简体   繁体   中英

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 :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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