简体   繁体   中英

How to compare instances of protocols and instances of classes

I have a protocol:

protocol MasterGame {}

and a class that produces a singleton

class MasterGameImp : MasterGame {
    static let sharedInstance = MasterGameImp()
}

Now I have another object that has a dependency on the protocol and has the property injected by it's instantiator.

class MyGameObject {
    var masterGame: MasterGame?
}

I want to write a unit test to test that the singleton is injected properly into an instance of MyGameObject. What is the right way to do this? === does not accept arguments of type MasterGame and MasterGameImp. So apparently you can't check sameness that way between a protocol and a class. So I need another way to check sameness between the singleton and the stored property. Thanks!

The issue very much simplified is the following:

protocol P {
}

class X : P {
}

let x = X()
let p : P = x

print(x === p)

Binary operator === cannot be applied to operands of type 'X' and 'P'

print((x as P) === p)

Binary operator === cannot be applied to two 'P' operands

print(x === (p as! X))

true -> Working

What you have to do is upcast the protocol to its implementation, which es really not pretty at all :/

I did not find a better solution, it has something to do how swift handles protocols different than regular class inheritance. Changing to class P will result in all three above statements to succeed.

As @matt noted the code will of course crash if you incorrectly provide a wrong p which is not really a X . To solve that issue you should wrap the check into a if-condition:

if let xp = p as? X {
    print(x === xp)
} else {
    print("p is not of type X")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM