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

'Protocol composition type' with generic types/inheritance

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Resolved
    • Priority: Medium
    • Resolution: Duplicate
    • Component/s: None
    • Labels:
      None

      Description

      I've been running into some problems with trying to use a 'protocol composition type' (e.g. MyType & MyProtocol, I'll refer to it as a PCT for brevity) with generics, both by trying to use it as a generic constraint and as the parameter to a generic type. This code sample more succinctly shows my problem in less technical words:

      protocol MyProtocol: AnyObject { }
      class MyClass { }
      class MySubclass: MyClass, MyProtocol { }
      class MyGenericClass<T> {
          func foo(with o: T) { }
      }
      extension MyGenericClass where T: MyClass {
          func bar(with o: T) { }
      }
      // this extension compiles. My understanding, though, is that it's treating the
      // PCT as a protocol to conform to rather than a class to inherit from
      extension MyGenericClass where T: MyClass & MyProtocol {
          func baz(with o: T) { }
      }
      
      // works fine; 'MySubclass' fills the requirement for 'MyClass & MyProtocol'
      // in this context
      var myClass: (MyClass & MyProtocol)?
      myClass = MySubclass()
      
      let i = MyGenericClass<MyClass>()
      i.foo(with: MySubclass())
      i.bar(with: MySubclass())
      
      let j = MyGenericClass<MyClass & MyProtocol>()
      j.foo(with: MySubclass())
      j.bar(with: MySubclass()) // error
      j.baz(with: MySubclass()) // error
      

      If I try to add a constraint on MyGenericClass.T that it must be an AnyObject, I get this error when I declare j: ''MyGenericClass' requires that 'MyClass & MyProtocol' be a class type". I expected that MySubclass would fill the type requirements on the last two lines, but it doesn't - is this intended, or just an overlooked detail due to the way PCTs are implemented?

      Thanks!

       

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              Aaron Bosnjak Aaron Bosnjak
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

                Dates

                Created:
                Updated:
                Resolved: