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

Erratic type inference makes it seem like an error can be detected at compile time or runtime or not at all

    XMLWordPrintable

    Details

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

      Default toolchain of Xcode 11.3.1 (11C504)

      Description

      Forum post and thread with further details:
      https://forums.swift.org/t/34044/6

      Demonstration Program A (shows expected behavior):

      struct G<T> { var value: T }
      func foo<T, R>(_ a: T, _ fn: (T) -> R) -> R { return fn(a) }
      
      let a: G<(id: Int,  data: String)> = G(value: (123, "abc"))
      let b: G<(id: Int, daata: String)> = foo(a) {
          return $0 // <-- Error here as expected (misspelled daata -> mismatched array types)
      }
      

      Demonstration Program B (shows unexpected behavior for Array):

      func foo<T, R>(_ a: T, _ fn: (T) -> R) -> R { return fn(a) }
      
      let a: [(id: Int,  data: String)] = [(123, "abc")]
      let b: [(id: Int, daata: String)] = foo(a) {
          // _ = () // <-- Uncomment this line to detect error on
          return $0 // <-- this line at compile- instead of run time.
      }
      

      Demonstration Program C (shows a different unexpected behavior for Optional):

      func foo<T, R>(_ a: T, _ fn: (T) -> R) -> R { return fn(a) }
      
      let a: (id: Int,  data: String)? = (123, "abc")
      let b: (id: Int, daata: String)? = foo(a) {
          // _ = () // <-- Uncomment for compile time error on the next line, but note that it will compile and run as long as this line is commented away.
          return $0 // <-- No runtime error here when it's `Optional<Tuple>` instead of `Array<Tuple>`.
      }
      print(b ?? "") // Prints `(id: 123, daata: "abc")`
      

        Attachments

          Activity

            People

            Assignee:
            Unassigned Unassigned
            Reporter:
            jens Jens Persson
            Votes:
            0 Vote for this issue
            Watchers:
            4 Start watching this issue

              Dates

              Created:
              Updated: