我想知道是否有一种更简单的方法将这两个初始化程序编写为通用的初始化程序
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标题:
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以采用通用协议并使该协议成为预期类型……