Reputation: 18298
I have created a protocol:
public protocol MyProtocol {
func doTask()
}
Then, I have an array for elements with MyProtocol
type:
var taskList: [MyProtocol] = []
Callers can add elements to taskList, eventually, I got an non-empty taskList
.
Now, I need to have a function that could remove an element from taskList
, this is what I tried:
func removeTask(task: MyProtocol) {
// Compiler error: Binary operator '!==' cannot be applied to two 'MyProtocol'
taskList = taskList.filter{$0 !== task}
}
But I get compiler error: Binary operator '!==' cannot be applied to two 'MyProtocol'
How to get rid of this error?
=== UPDATE ===
Thanks @holex, after changed MyProtocol
to be class-only, it works fine. But now I wonder if I need MyProtocol
to be not class-only, what would be the solution then?
Upvotes: 4
Views: 128
Reputation: 7703
You are using !==
which is comparing references. You can't compare protocol
directly using this operator, since MyProtocol
can become a class
or struct
. Since the !==
can only compare instances, you must explicitly declare that your protocol
is a class
.
Please change the MyProtocol
to the following, which should fix your problem:
protocol MyProtocol: class { // AnyObject can be used here as well
func doTask()
}
Trying to accomplish this without class
or AnyObject
will not work with your current design. You might want to implement another comparison method.
Also note that you can try to use !=
which might be able to do the exact same thing you want. Using this way you don't have to declare class
or AnyObject
. So check if that works for you.
Upvotes: 6