Do Int and Double share a common parent class in Swift

I am wondering if there is an easier way to write these two initializers as a standard initializer

public required init(_ value : Double) { super.init(value: value, unitType: unit) } public required init(_ value : Int) { let v = Double(value) super.init(value: v, unitType: unit) } 

Sort of:

 public init<T>(_value : T) { let v = Double(T) super.init(value: v, unitType: unit) } 

(which of course does not compile)

I looked at the code of both Int and Double, and I miss the real thing that ties them together.

+6
source share
1 answer

Take a look at the Swift header:

 extension String : StringInterpolationConvertible { init(stringInterpolationSegment expr: String) init(stringInterpolationSegment expr: Character) init(stringInterpolationSegment expr: UnicodeScalar) init(stringInterpolationSegment expr: Bool) init(stringInterpolationSegment expr: Float32) init(stringInterpolationSegment expr: Float64) init(stringInterpolationSegment expr: UInt8) init(stringInterpolationSegment expr: Int8) init(stringInterpolationSegment expr: UInt16) init(stringInterpolationSegment expr: Int16) init(stringInterpolationSegment expr: UInt32) init(stringInterpolationSegment expr: Int32) init(stringInterpolationSegment expr: UInt64) init(stringInterpolationSegment expr: Int64) init(stringInterpolationSegment expr: UInt) init(stringInterpolationSegment expr: Int) } 

Similarly:

 func +(lhs: UInt8, rhs: UInt8) -> UInt8 func +(lhs: Int8, rhs: Int8) -> Int8 func +(lhs: UInt16, rhs: UInt16) -> UInt16 func +(lhs: Int16, rhs: Int16) -> Int16 func +(lhs: UInt32, rhs: UInt32) -> UInt32 func +(lhs: Int32, rhs: Int32) -> Int32 func +(lhs: UInt64, rhs: UInt64) -> UInt64 func +(lhs: Int64, rhs: Int64) -> Int64 func +(lhs: UInt, rhs: UInt) -> UInt func +(lhs: Int, rhs: Int) -> Int func +(lhs: Float, rhs: Float) -> Float func +(lhs: Double, rhs: Double) -> Double func +(lhs: Float80, rhs: Float80) -> Float80 

If one could write one common function for all these different numerical types, they would do it, of course. Therefore, the answer to your question should not be.

(And in any case, they can hardly be shared by the parent class, since they are not classes. They are structures.)

Now, of course, if it is only about Int and Double, you can extend Int and Double to accept a common protocol and make this protocol the expected type ...

+8
source

Source: https://habr.com/ru/post/988092/


All Articles