user2195592 user2195592 - 6 months ago 14
Swift Question

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

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?

Answer

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