Uploaded image for project: 'Swift'
  1. Swift
  2. SR-2033

Better Error Messages When Not Inferring Closure Types



    • Type: Improvement
    • Status: Open
    • Priority: Medium
    • Resolution: Unresolved
    • Component/s: None
    • Labels:


      Since the type checker does not infer types for closures with more than 1 statement (a purposeful feature of the type checker, in order to keep performance up), the following code compiles:

      let a = [[1,2],[3],[4,5,6]]
      var b: [Int]
      b = a.flatMap { elem in
        return elem

      While this code gives the error: "cannot convert return expression of type '[Int]' to return type 'Int?'":

      b = a.flatMap { elem in
        return elem

      As the type checker seems to pick an implementation of flatMap and check against that, it tells us to use a different flatMap than we intended, even though our code is actually valid.

      I think that for users who aren't aware of this type checker limitation, this error message will be very confusing. Additionally, it could occur with many different functions, and you could also get the same message in a case where you actually aren't providing valid types.

      I propose that, in the case where the type checker does not infer the type of a multi-statement closure, yet finds an error with the types, it adds a more helpful message so the user is aware that their code might be valid, and they should explicitly declare the types in their closure. Something like "Did not infer types in multi-statement closure, try explicitly declaring them if you are expecting a different implementation".




            • Assignee:
              rosslebeau Ross LeBeau
            • Votes:
              1 Vote for this issue
              3 Start watching this issue


              • Created: