Imagine the following code:
protocol Expression {}
struct Number: Expression {
let value: Int
}
struct Product: Expression {
let factors: [Expression]
}
extension Number: ExpressibleByIntegerLiteral {
init(integerLiteral value: Int) {
self.init(value: value)
}
}
let p = Product(factors: [1, 2]) // won't compile, the compiler will assume 1 and 2 are of type Int
let p2 = Product(factors: [1 as Number, 2]) // this will compile
func makeNumberProduct(_ factors: Number...) -> Product {
return Product(factors: factors)
}
let p3 = makeNumberProduct(1, 2) // this will also compile
So it looks like type inference with the literal types only works if there is an explicit conversion to the exact type expected in an expression and not to a subtype. As soon as you add more context providing explicit type hints (even if its just on one expression in, say, an array), it starts working again.
Is that a known limitation in the compiler? Is this something that can be worked around?