swiftlang/swift

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

Open

#61,733 建立於 2022年10月26日

在 GitHub 查看
 (27 留言) (1 反應) (1 負責人)Swift (10,719 fork)batch import
Optionalcompilerdiagnostics qualityexistentialsgenericsgood first issuetype checker

倉庫指標

Star
 (69,989 star)
PR 合併指標
 (平均合併 8天 17小時) (30 天內合併 510 個 PR)

描述

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.

貢獻者指南