I've had a VehicleModels
framework with classes like Car
, Bike
, Plane
.
In the other framework VehicleInventory
I needed to print customised descriptions (specific to the second framework) in a table. So I have added protocol DescriptableVehicle
with method describe()
.
Then I've added protocol extensions for all the vehicles like:
extension Car: DescriptableVehicle {
func describe() -> String {
return "Car: \(self.vin)" // returns formatted vehicle number
}
}
However, assumptions have changed and now I do not expose concrete classes from my vehicles framework. Instead, I expose protocols like CarProtocol
, BikeProtocol
, so that in general I have the same information.
The problem is that I can't use protocol extensions anymore (or at least not in that shape) because extension of protocol in opposite to extension of class cannot have an inheritance clause.
Any idea how I can tackle the problem to not modify my usages to much?
Initially, I thought couple where
clauses on protocols plus couple casts will make the deal, however without access to classes it doesn't help.
I have also tried Adapters and type erasure but either I am using it badly or it serves a different purpose.
To illustrate problem I have prepared repository: https://github.com/wedkarz/SwiftProtocolExtensionsProblem
There are two playgrounds. V1 is what I used to have and which was working. V2 contains what I have now and what I am trying to make working.
In real life, class PrivateFramework
is a separate framework and protocols: VehicleProtocol
, CarProtocol
, BikeProtocol
, PlaneProtocol
are part of it, but DescriptableVehicle
is not a part of PrivateFramework
, so it cannot be used inside. The example illustrates a problem with accesses to concrete types and a problem with its extensions.
You can see there are extensions commented out because I cannot use them anymore. The goal is to make the collection of [VehicleProtocol]
printing its contents in a similar fashion it was working previously.