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

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的函数,而不会让编译器抱怨.

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...