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

'Generic parameter 'Result' could not be inferred' compiler error for wrapper functions like autoreleasepool that return the result of their closure argument.

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Open
    • Priority: Medium
    • Resolution: Unresolved
    • Component/s: Compiler
    • Labels:
    • Environment:

      Swift 2.2 in Xcode 7.3.1 (7D1014), and swift-DEVELOPMENT-SNAPSHOT-2016-05-09-a

      Description

      Hello,

      It's a very common pattern to write functions that take a closure and return this closure's result. An example is autoreleasepool, since SE-0061.

      The most simple one is:

      func f<Result>(_ closure:() -> Result) -> Result {
          return closure()
      }
      

      The issue is that Swift compiler (in both versions 2.2 and swift-DEVELOPMENT-SNAPSHOT-2016-05-09-a) outputs an error `Generic parameter 'Result' could not be inferred` whenever the closure contains a line of code followed with a return statement:

      do {
          // Variant 1
          // Generic parameter 'Result' could not be inferred
          let x = f {
              print("foo")
              return 1
          }
      }
      
      do {
          // Variant 2
          // Generic parameter 'Result' could not be inferred
          f {
              print("foo")
              return 1
          }
      }
      

      The workaround is to add explicit type declaration:

      do {
          // Workaround 1 for variant 1
          let x = f { _ -> Int in
              print("foo")
              return 1
          }
      }
      
      do {
          // Workaround 2 for variant 1
          let x: Int = f {
              print("foo")
              return 1
          }
      }
      
      do {
          // Workaround for variant 2
          f { _ -> Int in
              print("foo")
              return 1
          }
      }
      

      The problem is that this workaround is not easy to find for regular users: they complain and report issues.

      As for the variant 2 itself, which does not use the returned value, it can be the sign of some unfinished code, or of some actual issue: we need an "unused result" warning, not an error.

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                Unassigned
                Reporter:
                groue Gwendal Roué
              • Votes:
                0 Vote for this issue
                Watchers:
                5 Start watching this issue

                Dates

                • Created:
                  Updated: