2

SWIFT - How to compare the instance of a typed array with the protocol

 2 years ago
source link: https://www.codesd.com/item/swift-how-to-compare-the-instance-of-a-typed-array-with-the-protocol.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

SWIFT - How to compare the instance of a typed array with the protocol

advertisements

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


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 {

Tags swift

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK