1

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 }
    }
    
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
ios coder
  • 1
  • 4
  • 31
  • 91

1 Answers1

4

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.

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • thanks, what about `SignedNumeric` do I need this as well? – ios coder Apr 16 '21 at 01:10
  • 1
    `SignedNumeric` is more resctrictive. `Numeric` with extend signed and unsigned types as well as `FloatingPoint` types and `Decimal` – Leo Dabus Apr 16 '21 at 01:12
  • 1
    `SignedNumeric` will extend all `FloatingPoint` and `SignedInteger` types. [Protocol SignedNumeric](https://developer.apple.com/documentation/swift/signednumeric) – Leo Dabus Apr 16 '21 at 01:18
  • @swiftPunk `CGFloat` and `Decimal` conforms to `SignedNumeric` as well – Leo Dabus Apr 16 '21 at 01:24
  • I tried any possible number type, all working fine with `Numeric`, it covers everything. – ios coder Apr 16 '21 at 01:27
  • 1
    @swiftPunk yes it covers all numeric types. You will have a hard time when trying to use the division operator. If you need only addition you can extend `AdditiveArithmetic` protocol [Making my function calculate average of array Swift](https://stackoverflow.com/a/28288619/2303865) – Leo Dabus Apr 16 '21 at 01:28