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

时间:2015-05-28 13:25:58

标签: swift generics int double

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

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的代码,并且遗漏了将它们联系在一起的任何真实的东西。

1 个答案:

答案 0 :(得分: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)
}

类似地:

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

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

(在任何情况下,他们都很难共享父,因为它们不是。它们是结构体。)

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

相关问题