Home > other >  How to calculate percentage with generics in Swift?
How to calculate percentage with generics in Swift?

Time:08-09

I would do following conversion if width == 200 then

20 -> 40
20.0 -> 40.0

So it should work for both Int and Double.

let width = 333

func unitX<T>(x: T) -> T {
    return width * x / 100
}

but get this error:

Binary operator '*' cannot be applied to operands of type 'Int' and 'T'

What can I do?

CodePudding user response:

...If Generic is really the way you want to go with this:

You'll want to start by defining some constraints on T to constrain it to a type that make sense to take a percentage of. From there, you'll simply need to iterate the possibilities and cast, or define your own operator on a protocol you're conforming to.

You can read about custom operators here: https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html

In theory you could do something like this:

protocol Percentable {
    var value: Double {get, set}
}

extension Percentable {
    static prefix func % () -> Percentable {
        // DO percentage logic here 
        return value
    }
}

And then you could call this like the following:

func unitX<T>(x: T) -> T where T: Percentable {
    return x %
}

Note: You would have to then make an extension on Int or Double to be Percentable.

Recap

This would be a horrible approach since you would simply be converting from and Int to a Double back to an Int. It would make more sense (like mentioned in the comments) to simply overload Ints to divide by Doubles and visa-versa to keep your precision. Generics are not a good use here.

  • Related