0

While playing around with the code in another SO post, I found this interesting behaviour.

As we know, the type of a weak var needs to be a class type and the type used in a generic constraint needs to be a class type, or a protocol type.

Therefore, this does not compile:

class Foo<T> {
    weak var bar: T? // error
    func foo<U: T>(u: U) {} // error
}

According to this post, I can put an AnyObject constraint (or any protocol that has a : class constraint) on T to remove the first error:

class Foo<T: AnyObject> {
    weak var bar: T?
    func foo<U: T>(u: U) {} // error
}

But the second error still remains:

Type 'U' constrained to non-protocol, non-class type 'T'

The compiler seems to be lying through its teeth right here. By removing the first error the compiler has just admitted that T indeed is a class type, and now it's saying it isn't.

Why is this happening? Did they just not design this feature?

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • Is there any situation where you can chain generic parameters like that, ``? – Joakim Danielson Jan 10 '20 at 16:21
  • @JoakimDanielson It came from a failed attempt of me trying to simulate some generic variance in Swift, which I know is only supported for arrays. – Sweeper Jan 10 '20 at 16:24
  • 1
    I added `U: AnyObject` to the class header and still got the same error. To me it looks like the limitation is that you can’t constrain a generic parameter with another generic parameter (in any situation). – Joakim Danielson Jan 10 '20 at 16:34
  • So it's another case of confusing error messages, then? It should have said something like "generic parameters are not allowed to be used as generic constraints". @JoakimDanielson – Sweeper Jan 10 '20 at 16:38

0 Answers0