加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 05:39:03 所属栏目:百科 来源:网络整理
导读:我想知道是否有一种更简单的方法将这两个初始化程序编写为通用的初始化程序 public required init(_ value : Double) { super.init(value: value,unitType: unit)}public required init(_ value : Int) { let v = Double(value) super.init(value: v,unitTyp
我想知道是否有一种更简单的方法将这两个初始化程序编写为通用的初始化程序
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以采用通用协议并使该协议成为预期类型……

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读