0
votes

I'm new to Swift code and sorry for my bad english. Here is my code:

var t = Array<MyClassProtocol> ()
var instance1 = MyClasse () //protocol MyClassProtocol
var instance2 = MyClasse () //protocol MyClassProtocol 
var instance3 = MyClasse2 () //protocol MyClassProtocol 
t.append (instance1)
t.append (instance2)
t.append (instance3)

//What I try to do 

for instance in t
{
    if (instance === instance1){ /* do something */ }
}

XCode return : type MyClassProtocol does not conform to protocol "AnyObject"

Any Idea ? Thanks

4
Can we also see the classes MyClasse and MyClasse2James Webster

4 Answers

1
votes

The === operator can be applied only to instances of classes. However, Swift doesn't have only classes, it also has structs. Structs can also adopt MyClassProtocol. The problem is that when Swift sees instance only as a MyClassProtocol, it doesn't know whether it is a struct or a class, so you cannot use ===.

To solve it, you need to prevent MyClassProtocol from being adopted by structs. This is done by letting it inherit from AnyObject (which is an empty class protocol).

protocol MyClassProtocol : AnyObject {
0
votes

You need to let MyClassProtocol inherit from AnyObject

protocol MyClassProtocol : AnyObject {

}
0
votes

I think you MyclassProtocol not inherit from AnyObject. so try this: it is maybe work.

protocol MyClassProtocol:AnyObject{ // make sure  you protocol inherit from AnyObject
 func doSomething()
} 




class Myclass:MyClassProtocol{
 func doSomething() {

 }
}

class Myclass2: MyClassProtocol {
 func doSomething() {

 }
} 
var t = Array<MyClassProtocol>()
var instance1 = Myclass () //protocol MyClassProtocol
var instance2 = Myclass () //protocol MyClassProtocol
var instance3 = Myclass2 () //protocol MyClassProtocol
t.append (instance1)
t.append (instance2)
t.append (instance3)


for instance in t{
  if (instance === instance1){

 }
}
-1
votes

Your classes will need to implement the protocol MyClassProtocol

e.g.

class MyClasse: NSObject, MyClassProtocol
                          ^ Here we tell the class that it should implement the protocol

Just as an aside, you can also declare your arrays like this:

var t : [MyClassProtocol] = [];