简体   繁体   English

如何比较协议实例和类实例

[英]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. 我想编写一个单元测试来测试单例是否已正确注入MyGameObject实例中。 What is the right way to do this? 什么是正确的方法? === does not accept arguments of type MasterGame and MasterGameImp. ===不接受MasterGame和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' 二进制运算符===不能应用于类型'X'和'P'的操作数

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

Binary operator === cannot be applied to two 'P' operands 二进制运算符===不能应用于两个'P'操作数

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. 我没有找到更好的解决方案,它与swift处理不同于常规类继承的协议有关。 Changing to class P will result in all three above statements to succeed. 更改为class P将导致以上所有三个语句成功。

As @matt noted the code will of course crash if you incorrectly provide a wrong p which is not really a X . 正如@matt所指出的,如果您错误地提供了一个错误的p(实际上不是X那么代码当然会崩溃。 To solve that issue you should wrap the check into a if-condition: 要解决该问题,您应该将支票包装为if条件:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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