1

Tinkering around with this question, I came up with this:

class AllTogether<T: FooProtocol> {
    func createContainer<U: T>(data: U){
        Container<T>(someDataConformingFooProtocol: data)
    }
}

My understanding is that this should work if we make FooProtocol a class protocol:

protocol FooProtocol: class { ... }

However, we still get errors:

Error: inheritance from non-protocol, non-class type 'T'
Error: argument type 'U' does not conform to expected type 'FooProtocol'

Both messages seem to be wrong. What am I missing?

Is the subtype relation not transitive in Swift?

Community
  • 1
  • 1
Raphael
  • 9,779
  • 5
  • 63
  • 94

1 Answers1

0

The function adds an additional relation that is unnecessary.

Container is looking to be initialized with an object of type T.

If U is a subclass of T, then anything that can be called with

func createContainer<U: T>(data: U)

can also be called with

func createContainer(data: T)

So basically what the function is doing seems like it should be possible (and may be at some point. Swift's generics is due to be overhauled/improved) but it is pointless anyway.

Just use this instead:

func createContainer(data: T){
    Container<T>(someDataConformingFooProtocol: data)
}
GetSwifty
  • 7,568
  • 1
  • 29
  • 46
  • You'll note that what you proposed is used in the question I link, and causes (similarly weird) errors elsewhere. In that case, what I do is not necessary. I guess I was thinking of signatures I saw in Scala's standard library. Off the top of my head, I can imagine signatures like `func foo(u: U, v: V) where U: V` (for whatever travesty you'd need that) or, more simply, `func foo(u: U) where U: Hashable` (or any other "utility" protocol `T` does not extend itself). – Raphael Jan 11 '17 at 19:16
  • Come to think of it, `==(lhs: U, rhs: U) where U: Equatable` seems a reasonable thing to want (be able to write down; not saying that would be the prefered way of defining that equality operator). – Raphael Jan 11 '17 at 19:17
  • The plan is to add Conditional Conformance for Swift 4: https://github.com/apple/swift-evolution/blob/master/proposals/0143-conditional-conformances.md It seems likely this type of issue will be fixed then. – GetSwifty Jan 11 '17 at 20:08
  • Yay! There seem to be many issues around type parameters in Swift, hopefully they'll fix a bunch along the way. – Raphael Jan 11 '17 at 21:18
  • Yeah, there are a lot of quirks and holes in how generics and extensions work. hopefully it'll all be nice and tidy in the next year or two :) – GetSwifty Jan 12 '17 at 00:28