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

Generic constraint fails to infer type when expecting sub protocol

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Resolved
    • Priority: Medium
    • Resolution: Done
    • Component/s: Compiler
    • Labels:
      None
    • Environment:

      Description

      When trying to receive a sub-protocol from a generic method constrained by a parent protocol, the compiler fails, returning an error saying that the "Generic parameter 'T' could not be inferred":

       protocol Parent {
           var title: String { get }
       }
      
      protocol Child: Parent {
           var subtitle: String { get }
       }
      
      func genericConstraint<T: Parent>(options: [String: Any], completion: (T)->Void) {
           //Create concrete implementation based on options passed
       }
      
      //The compiler fails to accept 'Child' as type with the error message "Generic parameter 'T' could not be inferred"
       genericConstraint(options: [:]) { (child:Child) in
           //The compiler mistakenly throws the error "Ambiguous reference to member 'print(_:separator:terminator)'"
           print(response.subtitle)
       }
      

      This constraints could be useful when having multiple types (like structs Child1, and Child2) that could be create based on different options, also, when "hidding" types under protocol, like abstracting CoreData implementation from other app layers.

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              igorcferreira Igor Castañeda Ferreira
              Reporter:
              igorcferreira Igor Castañeda Ferreira
              Votes:
              1 Vote for this issue
              Watchers:
              3 Start watching this issue

                Dates

                Created:
                Updated:
                Resolved: