Why does type annotation for Int as Double work but not Double as Int?

Viewed 134

In Swift, a type annotation works to make an integer a double

  let num: Double = 100
  print(num)

Why does a type annotation not do the same for a double to integer (error of cannot convert value of type 'Double' to specified type 'Int')?

  let num: Int = 100.0
  print(num)
1 Answers

Converting an Int literal to a Double works solely because Double conforms to 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.

For the second code to work, Int would have to conform to ExpressibleByFloatLiteral.

extension Int : ExpressibleByFloatLiteral {
    public typealias FloatLiteralType = Double

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

let a: Int = 100.0 // works

I don't particularly recommend doing this though. This might cause you to accidentally pass a double value to a function expecting an Int, without the compiler complaining.

Related