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

前端之家收集整理的这篇文章主要介绍了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的函数,而不会让编译器抱怨.

猜你在找的Swift相关文章