Is there a way to convert any generic Numeric into a Double?

前端 未结 2 1067
清酒与你
清酒与你 2020-12-20 16:05

So I have a method that has 3 different types of arguments that could come in:

Int32, Int and Double. So the idea was to use

相关标签:
2条回答
  • 2020-12-20 16:48

    ... because there is no initializer for Double that takes a Generic.

    That is not entirely true. There is no initializer taking a Numeric argument. But there are generic initializers taking BinaryInteger and BinaryFloatingPoint arguments, so that two overloads are sufficient:

    func resetProgressBarChunks<T: BinaryInteger>(originalIterationCount: T) {
        let iCount = Double(originalIterationCount)
        // ...
    }
    
    func resetProgressBarChunks<T: BinaryFloatingPoint>(originalIterationCount: T) {
        let iCount = Double(originalIterationCount)
        // ...
    }
    

    This covers Double, Int, Int32 arguments as well as Float and all other fixed-size integer types.

    0 讨论(0)
  • 2020-12-20 16:49

    Just for purposes of syntactical illustration, here's an example of making this a generic and arriving at a Double for all three types:

    func f<T:Numeric>(_ i: T) {
        var d = 0.0
        switch i {
        case let ii as Int:
            d = Double(ii)
        case let ii as Int32:
            d = Double(ii)
        case let ii as Double:
            d = ii
        default:
            fatalError("oops")
        }
        print(d)
    }
    

    But whether this is better than overloading is a matter of opinion. In my view, overloading is far better, because with the generic we are letting a bunch of unwanted types in the door. The Numeric contract is a lie. A triple set of overloads for Double, Int, and Int32 would turn the compiler into a source of truth.

    0 讨论(0)
提交回复
热议问题