Int 和 Double 在 Swift 中共享一个共同的父 class

Do Int and Double share a common parent class in Swift

我想知道是否有更简单的方法将这两个初始化程序编写为通用初始化程序

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)
}

类似于:

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

(当然不能编译)

我查看了 Int 和 Double 的代码,遗漏了任何将它们联系在一起的真实事物。

看看 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)
}

同样:

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

如果可以为 all 那些不同的数字类型编写 one 通用函数,他们肯定会这样做。所以你的问题的答案一定是No.

(而且无论如何他们都很难共享一个 parent class,因为他们不是 class es。它们是结构。)

现在,当然,如果只有 Int 和 Double 有问题, 可以扩展 Int 和 Double 以采用通用协议并使该协议成为预期的类型...