Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Check if Two Objects Conforming to a Protocol Are Referentially The Same

Tags:

types

swift

I have a protocol that forms the base of many classes—in the example below, StaticFile and RemoteFile. I have a reference to a variable that points to the protocol

protocol ContainerDelegate {}

protocol FileProtocol {
    var delegate: ContainerDelegate? { get set }
}

class StaticFile: NSObject, FileProtocol {
    var delegate: ContainerDelegate?
}
class RemoteFile: NSObject, FileProtocol {
    var delegate: ContainerDelegate?
}

class Container: NSObject, ContainerDelegate {
    var item: FileProtocol

    override init() {}

    func something() {
        if item.delegate !== self { // This fails
        }
    }
}

I don’t even care about types really, I only want to see if the delegate is not the current object (by reference). What’s the best way to make the failing line work correctly?

like image 624
Jacob Avatar asked Mar 13 '23 02:03

Jacob


1 Answers

You should try to upcast the delegate and then check for equality:

func something() {
    if item.delegate as? Container !== self {
        print("hi")
    }
}

Full working code example

protocol ContainerDelegate {}
protocol FileProtocol {
    var delegate: ContainerDelegate? { get set }
}

class StaticFile: NSObject, FileProtocol {
    var delegate: ContainerDelegate?
}

class Container: NSObject, ContainerDelegate {
    var item: FileProtocol

    func something() {
        if item.delegate as? Container !== self {
            print("hi")
        }
    }

    override init() {
        item = StaticFile()
    }
}

let c = Container()
let c2 = Container()

c.item.delegate = c2
c.something() // hi gets printed

c.item.delegate = c
c.something() // hi does **not** get printed
like image 57
luk2302 Avatar answered May 03 '23 14:05

luk2302