I'm trying to write a protocol that reconciles two different structs that describe the same concept, a stop of some kind. Both have a Code
, Description
, and Latitude
& Longitude
coordinates, but for one type, the Description
could be nil
, and for the other type, the coordinates might be nil
.
How can I write a single protocol that reconciles these two structs?
Here's my protocol:
protocol Stop {
var Code : String { get }
var Description : String { get }
var Latitude : Double { get }
var Longitude : Double { get }
}
And the two types of stops:
struct BusStop : Stop { // Compiler error: doesn't implement Description
var Code : String
var Description : String?
var Latitude : Double
var Longitude : Double
// Various other properties
}
struct TrainStop : Stop { // Compiler error: doesn't implement Latitude or Longitude
var Code : String
var Description : String
var Latitude : Double?
var Longitude : Double?
// Various other properties
}
In C# (my mother tongue), I would write an explicit interface implementation like so (pseudo-code):
// At the end of the BusStop struct
var Stop.Description : String { return Description ?? string.Empty }
// At the end of the TrainStop struct
var Stop.Latitude : Double { return Latitude ?? 0 }
var Stop.Longitude : Double { return Longitude ?? 0 }
However, I'm not aware of any similar functionality in Swift. Given that I'm unable to change the existing property definitions of BusStop
and TrainStop
, how can I write the Stop
protocol so that it wraps around both structs and returns the properties when available?