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

swift – 为什么类型注释为Int作为Double工作而不是Double作为In

发布时间:2020-12-14 04:25:37 所属栏目:百科 来源:网络整理
导读:在 Swift中,类型注释用于使整数为double let num: Double = 100 print(num) 为什么类型注释不能对double到整数执行相同的操作(错误不能将’Double’类型的值转换为指定类型’Int’)? let num: Int = 100.0 print(num) 解决方法 将Int文字转换为Double只是因
在 Swift中,类型注释用于使整数为double

let num: Double = 100
  print(num)

为什么类型注释不能对double到整数执行相同的操作(错误不能将’Double’类型的值转换为指定类型’Int’)?

let num: Int = 100.0
  print(num)

解决方法

将Int文字转换为Double只是因为Double符合 ExpressibleByIntegerLiteral

The standard library integer and floating-point types,such as Int and Double,conform to the ExpressibleByIntegerLiteral protocol. You can initialize a variable or constant of any of these types by assigning an integer literal.

要使第二个代码起作用,Int必须符合ExpressibleByFloatLiteral.

extension Int : ExpressibleByFloatLiteral {
    public typealias FloatLiteralType = Double

    public init(floatLiteral value: Int.FloatLiteralType) {
        self.init(value)
    }
}

let a: Int = 100.0 // works

我不特别推荐这样做.这可能会导致您意外地将double值传递给期望Int的函数,而不会让编译器抱怨.

(编辑:李大同)

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

    推荐文章
      热点阅读