Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift cast object to type and protocol at the same time

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?

Thanks

like image 388
Salman Hasrat Khan Avatar asked Aug 16 '16 15:08

Salman Hasrat Khan


2 Answers

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

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

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

protocol _NSManagedObject {
    //the methods you want
}

extension NSManagedObject: _NSManagedObject {}

extension Identifiable where Self: _NSManagedObject, Self: JsonParseDescriptor {
    func someMethod() { }
}
like image 21
Alexander Avatar answered Nov 11 '22 05:11

Alexander


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:

var myVar = otherVar as! (Type & Protocol)

No more need for extensions and bridge protocols.

like image 106
Hexfire Avatar answered Nov 11 '22 07:11

Hexfire