Swift同时将对象转换为类型和协议

时间:2022-06-01 20:58:55

How can I cast a given object to a type and a protocol in order to call some methods that are defined as an extension

如何将给定对象强制转换为类型和协议,以便调用某些定义为扩展名的方法

For Example:

extension Identifiable where Self: NSManagedObject, Self: JsonParseDescriptor {
    func someMethod() { }
}

Now I have an object that I retrieved from Core data and I would like to cast it to the above protocols in order to call someMethod on it. I could cast to the protocols using protocol<Identifiable, JsonParseDescriptor> , but how can I include the NSManagedObejct type in it also?

现在我有一个从Core数据中检索到的对象,我想把它转换为上面的协议,以便在它上面调用someMethod。我可以使用协议 来转换为协议,但是如何在其中包含NSManagedObejct类型呢? ,jsonparsedescriptor>

Thanks

2 个解决方案

#1


2  

What you're looking for it called a concrete same-type requirement. Unfortunately, it's not yet possible in Swift.

你正在寻找什么叫做具体的同类型要求。不幸的是,它在Swift中还不可能。

See ticket SR-1009 and SR-1447 for details. You should also checkout this answer.

有关详细信息,请参见SR-1009和SR-1447。你也应该看看这个答案。

In the mean-while, you can extend NSManagedObject with a dummy protocol with the methods you need:

同时,您可以使用您需要的方法使用伪协议扩展NSManagedObject:

protocol _NSManagedObject {
    //the methods you want
}

extension NSManagedObject: _NSManagedObject {}

extension Identifiable where Self: _NSManagedObject, Self: JsonParseDescriptor {
    func someMethod() { }
}

#2


1  

As of Swift 4, it is now possible to make mentioned cast directly without tricky workarounds. The task is accomplished similarly as we do protocol composition:

从Swift 4开始,现在可以直接进行提到的转换而无需棘手的解决方法。任务完成与协议组成类似:

var myVar = otherVar as! (Type & Protocol)

No more need for extensions and bridge protocols.

不再需要扩展和桥接协议。

#1


2  

What you're looking for it called a concrete same-type requirement. Unfortunately, it's not yet possible in Swift.

你正在寻找什么叫做具体的同类型要求。不幸的是,它在Swift中还不可能。

See ticket SR-1009 and SR-1447 for details. You should also checkout this answer.

有关详细信息,请参见SR-1009和SR-1447。你也应该看看这个答案。

In the mean-while, you can extend NSManagedObject with a dummy protocol with the methods you need:

同时,您可以使用您需要的方法使用伪协议扩展NSManagedObject:

protocol _NSManagedObject {
    //the methods you want
}

extension NSManagedObject: _NSManagedObject {}

extension Identifiable where Self: _NSManagedObject, Self: JsonParseDescriptor {
    func someMethod() { }
}

#2


1  

As of Swift 4, it is now possible to make mentioned cast directly without tricky workarounds. The task is accomplished similarly as we do protocol composition:

从Swift 4开始,现在可以直接进行提到的转换而无需棘手的解决方法。任务完成与协议组成类似:

var myVar = otherVar as! (Type & Protocol)

No more need for extensions and bridge protocols.

不再需要扩展和桥接协议。