swift: Improve the error message for passing `(any P)?` to `(some P)?`

If you try to pass a value of type (any P)? to an argument of type (some P)?, the compiler tells you that any P cannot conform to P, which is confusing and not actionable. With SE-0375, existential opening/unboxing is supported with optionals, but only if the argument is not an optional because it’s possible that the (any P)? is nil (and thus does not have a dynamic type to bind to some P). With SE-0375, the fix is to unwrap the optional or provide a default value. So, the error message should tell you that!

protocol P {}

struct S: P {}

func takesOptionalP(_: (some P)?) {}

func passOptional(value: (any P)?) {
  takesOptionalP(value) // error: type 'any P' cannot conform to 'P'

  takesOptionalP(value ?? S()) // okay under SE-0375
  takesOptionalP(value!) // okay under SE-0375
}

The constraint system currently applies the MissingConformance fix when solving for the takesOptionalP(value) expression. Instead, it should identify that the wrapped type of the argument matches the parameter type, and apply the ForceOptional fix.

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Reactions: 1
  • Comments: 23 (8 by maintainers)

Commits related to this issue

Most upvoted comments

I’ve created a draft PR here: https://github.com/apple/swift/pull/63667. It by no means solves the issue, but I’ve written a comment explaining where I’m struggling.

I will take another stab at it sometime later when I have the time, but any pointers would be appreciated @LucianoPAlmeida @hborla @AnthonyLatsis 🙂

Also @Rajveer100 feel free to chime in if you have any ideas.

This issue seems really interesting to grind! Let me try and find a solution to it!

I’ll still be working on it, but I have other things on my plate as well, so if you find a solution first, that’s fine too 🙂

Go for it! I worked on it for a while but never quite figured it out.

@hborla, I would love to work on it. But I’m completely new to this repo (and open source contribution in general). It would be very kind of you tell me how do I go about it