![](/img/trans.png)
[英]Swift 3: Is there a way to cast an object to a class and protocol at the same time?
[英]Swift cast object to type and protocol at the same time
如何將給定對象強制轉換為類型和協議,以便調用某些定義為擴展名的方法
例如:
extension Identifiable where Self: NSManagedObject, Self: JsonParseDescriptor {
func someMethod() { }
}
現在我有一個從Core數據中檢索到的對象,我想將它轉換為上述協議,以便在其上調用someMethod。 我可以使用protocol<Identifiable, JsonParseDescriptor>
來轉換為協議,但是如何在其中包含NSManagedObejct類型呢?
謝謝
你正在尋找什么叫做具體的同類型要求 。 不幸的是,它在Swift中還不可能。
有關詳細信息,請參閱票證SR-1009和SR-1447 。 你也應該看看這個答案。
同時,您可以使用您需要的方法使用偽協議擴展NSManagedObject
:
protocol _NSManagedObject {
//the methods you want
}
extension NSManagedObject: _NSManagedObject {}
extension Identifiable where Self: _NSManagedObject, Self: JsonParseDescriptor {
func someMethod() { }
}
從Swift 4開始 ,現在可以直接制作提到的演員而無需棘手的解決方法。 任務完成與協議組成類似:
var myVar = otherVar as! (Type & Protocol)
不再需要擴展和橋接協議。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.