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

Jee*_*eef 8 generics double int 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)
}
Run Code Online (Sandbox Code Playgroud)

就像是:

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

(当然不编译)

我查看了Int和Double的代码,并且遗漏了将它们联系在一起的任何真实的东西.

mat*_*att 11

看一下Swift标题:

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)
}
Run Code Online (Sandbox Code Playgroud)

同理:

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
Run Code Online (Sandbox Code Playgroud)

如果可以为所有那些不同的数字类型编写一个通用函数,他们肯定会这样做.所以问题的答案必须是否定的.

(无论如何,他们很难共享父类,因为它们不是类.它们是结构.)

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

  • 这是一个误导性的答案.这取决于用例.虽然这些类型需要它们自己的加法运算符,但完全可以在所有整数之间定义广泛的操作类,例如`func sum <S:SequenceType where S.Generator.Element:IntegerType>(seq: S) - > S.Generator.Element {return reduce(seq,0){$ 0 + $ 1}}`.也就是说,很少有协议可以在整数和浮点数之间建立桥接. (5认同)
  • @AirspeedVelocity 实际上我只是在等你过来并给出正确的答案。请给吧! (3认同)