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?