swiftlang / swift

The Swift Programming Language
https://swift.org
Apache License 2.0
67.27k stars 10.33k forks source link

Existential type conforming to `AnyObject` can't satisfy a generic parameter which conforms to `AnyObject` #72897

Open zetasq opened 5 months ago

zetasq commented 5 months ago

Description

After declaring a generic parameter T which conforms to AnyObject, I can't fulfill it with an existential type any P where P conforms to AnyObject.

Reproduction

import Foundation

public protocol P: AnyObject {}

public struct WeakRef<T: AnyObject> {
    weak var object: T?

    init(_ object: T) { self.object = object }
}

let weakRef: WeakRef<any P> // Error: 'WeakRef' requires that 'any P' be a class type

Expected behavior

The code above should compile successfully.

Environment

Swift 5.10

Additional information

No response

pyrtsa commented 3 months ago

Just bumped into the same restriction as well. It seems odd that existential types aren't more flexible w.r.t. AnyObject.

If it helps, the limitation can be worked around in some cases by marking the protocol @objc, as pointed out in this thread on Apple Developer Forums as well as manifested in Swift unit tests: test/Generics/existential_restrictions.swift.