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

前端 未结 2 1081
清酒与你
清酒与你 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(originalIterationCount: T) {
        let iCount = Double(originalIterationCount)
        // ...
    }
    
    func resetProgressBarChunks(originalIterationCount: T) {
        let iCount = Double(originalIterationCount)
        // ...
    }
    

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

提交回复
热议问题