Hi folks. I am facing the following situation:
My application defines a contract through a protocol:
public protocol Project {
var name: String
}
The application uses an external Obj-C library which provides a compatible type:
@interface CProject : NSObject
@property (nonatomic, readonly, nonnull) NSString *name;
@end
The intention is to use the existential any Project
throughout my application, so as to hide the concrete business implementation from the view. To that end, I can:
extension CProject: Project {}
Fantastic.
However, we run into an unfortunate quirk in Swift when we try to import the following perfectly conforming type:
@interface CTask : NSObject
@property (nonatomic, readonly, nonnull) CProject *project;
@end
public protocol Task {
var project: any Project
}
extension CTask: Task {} // type 'CTask' does not conform to protocol 'Task'
In reality, of course, CProject
is perfectly conforming to any Project
, so implicitly downcasting CProject
to the existential Project
in the compiler would solve the problem. Alas, this is not how Swift works right now. I need to declare the type explicitly:
extension CTask: Task {
var project: any Project { /* magic */ }
}
The question now becomes: is there any way for me to access the project: CProject
on CTask
that I just shadowed in my extension, in order to pass it back at this level? Is this sane?
Related: Using subtypes in the implementation of protocol properties and function return values