TransWikia.com

Trying build a func for multiply which accept any type numbers to work

Stack Overflow Asked by swiftPunk on February 25, 2021

I want to build a func which can take CGFloat, Double or Int as Input and return the multiply answer depending on input values types, like this code:

Update: I noticed that my explaining was not sharp enough,sorry, so I am explaining here, I do not want my return type be fixed to Double or Int or CGFloat, my return type is dynamic and depend on lhs and rhs! If one of those input is type CGFloat, then return type would be definitely CGFloat, but if function was not able detect any CGFloat type, then it will try the same thing for Double, and At least for Int, this function will return nil for any other type than Int, Double or CGFloat.

I could made mistakes with choosing Numeric I wanted function be open to accept any kind of number types like Int, Double, CGFloat, And the reason I chose T and U it was this: lhs could be Int and rhs could be Double or CGFloat. or opposite.

The user of function could be able for example load Int to lhs, and CGFloat to rhs and get answer in CGFloat type or:
The user of function could be able for example load Double to lhs, and Int to rhs and get answer in Double type.

    func advancedMultiply<T: Numeric, U: Numeric> (lhs: T, rhs: U) -> Numeric? {


    if (type(of: lhs) == CGFloat.self) || (type(of: rhs) == CGFloat.self) {

        return CGFloat(lhs)*CGFloat(rhs)

    }
    else if (type(of: lhs) == Double.self) || (type(of: rhs) == Double.self) {
        
        return Double(lhs)*Double(rhs)

    }
    else if (type(of: lhs) == Int.self) && (type(of: rhs) == Int.self) {
        
        return lhs*rhs
        
    }
    else {
        
        return nil
        
    }

}

I tried my best to make it working, but it has errors to compile, i need help to find the right way.

One Answer

First, it's BinaryInteger, not Numeric

Second, T and U conform to the same Protocol does not mean they will be the same type. So that, your return value is incorrect. Try a different value, such as: Bool, String, Int,...

You can find more information here

Answered by Andeevy on February 25, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP