Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error "Redundant constraint 'Self' : 'AnyObject'" - where is the `AnyObject`?

Tags:

swift

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?

like image 479
Michael Avatar asked Sep 20 '25 11:09

Michael


1 Answers

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.

like image 125
Rob Napier Avatar answered Sep 23 '25 02:09

Rob Napier