Int?(nil) is compiled, Int?.init(nil) is not compiled

Hello, I'm wondering what is difference between below two expresssions:

  • Int?(nil) -> compiled, nil

  • Int?.init(nil) -> not compiled

  • Int??(nil) -> compiled, nil

  • Int??.init(nil) -> compiled, Optional(nil)

I checked the documentation about Optional, and seems I use same initializer for all expressions. but there are differences. anyone knows why?

That's looks like a compiler's limit. You should ask the question on Swift.org.

Int?.init(nil) -> not compiled

Compiler is expecting an Int (why? that's the question), so it does not compile

Int??.init(nil)

Here, compiler is expecting Int?, so it compiles

So it seems that when using .init on an optional, compiler is expecting a value of the base class. Which is surprising as it is explained in doc that .init is equivalent to ()…

thank you. i am continuing to analyze this problem, such a interesting one.

I made a custom type that conforms ExpressibleByNilLiteral and tested some expressions.

struct A: ExpressibleByNilLiteral {
  init(nilLiteral: ()) {}
}

let a0: A? = nil // nil
let a1 = A?(nil) // nil
let a2 = A?(nilLiteral: ()) // nil
let a3 = A?.init(nil) // compile error
let a4 = A?.init(nilLiteral: ()) // nil

let a5 = A??(nil) // nil
let a6 = A??.init(nil) // Optional(nil)

let a7 = A???(nil) // nil
let a8 = A???.init(nil) // Optional(nil)

so i just thought that passing a nil literal without specifying init is equivalent to calling init(nilLiteral:), but specifying init and passing a nil literal is equivalent to calling init(_:).

in nested optional case, result of A??(nil) is nil, because it is guessed that it called init(nilLiteral:). and result of A??.init(nil) is Optional(nil), because it is guessed that it called init(_:).

it is just an assumption, i also wonder if this inference makes sense

Int?(nil) is compiled, Int?.init(nil) is not compiled
 
 
Q