如何将给定对象强制转换为类型和协议,以便调用某些定义为扩展名的方法
例如:
extension Identifiable where Self: NSManagedobject,Self: JsonParseDescriptor { func someMethod() { } }
现在我有一个从Core数据中检索到的对象,我想将它转换为上述协议,以便在其上调用someMethod.我可以使用协议< Identifiable,JsonParseDescriptor>转换为协议.,但是如何在其中包含NSManagedobejct类型呢?
谢谢
解决方法
你正在寻找什么叫做具体的同类型要求.不幸的是,它在Swift中还不可能.
有关详细信息,请参见SR-1009和SR-1447.你也应该结账this answer.
同时,您可以使用您需要的方法使用伪协议扩展NSManagedobject:
protocol _NSManagedobject { //the methods you want } extension NSManagedobject: _NSManagedobject {} extension Identifiable where Self: _NSManagedobject,Self: JsonParseDescriptor { func someMethod() { } }