I found a strange Swift compiler message while developing (I'm using Swift 4.1):
protocol Foo: class where Self: NSObject { // (1)
// Redundant constraint 'Self' : 'AnyObject'
}
What is happening here?
First, this is not redundant. When I write
protocol Foo: class { } // (2)
I have a protocol that any object could potentially conform to, even objects that don't derive from NSObject
. But I can create weak references: weak var f: Foo?
is okay.
On the other hand, when I write
protocol Foo where Self: NSObject { } // (3)
I have a protocol where I cannot produce weak references: weak var f: Foo?
is a compile time error.
Second, where does the AnyObject
come from? I'm asking for NSObject
. The NSObject
is respected though: I cannot declare a class MyFoo: Foo { }
because it rightly complains that it must inherit from NSObject
?
Is this a bug in Swift? Or am I missing something? If it is a bug: is it a bug because snippet (3) does not let me take weak references? Or because of the compiler warning? Or both? And if I am missing something: what is it?
It is not possible to constrain a protocol to be subclasses of a specific class in Swift 4.1. You can inherit Foo
from NSObjectProtocol
, which probably matches your intent.
protocol Foo: NSObjectProtocol {
// ....
}
In Swift 4.2, what you've written is legal Swift and does what you expect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With