Say I have three different managed objects. Each type of object has identical properties. I would like to write a method that will accept any one of the three objects and assign values to their properties.
let car = Car(context: context)
let boat = Boat(context: context)
let plane = Plane(context: context)
getDistanceTraveled(vehicle: car)
func getDistanceTraveled(vehicle: NSManagedObject) {
let newVehicle = vehicle as? Car //Instead of Car I want to cast this as the type being passed in.
newVehicle.distanceTraveled = 43
}
Usually, following the composite reuse principle (composition over inheritance), I would suggest using a protocol for a problem like this e.g.
protocol Vehicle {
var distanceTraveled: Float { get set }
}
struct Car: Vehicle {
var distanceTraveled: Float
}
struct Boat: Vehicle {
var distanceTraveled: Float
}
Then pass a Vehicle
into your function:
func getDistanceTravelled(vehicle: Vehicle) -> Float {
return vehicle.distanceTraveled
}
However, I think this is more complex than what is described above as the Car
, Boat
and Plane
objects are managed by Core Data and are a subclass of NSManagedObject
.
Whilst there are ways to deal with this, e.g.
I would instead suggest creating a Vehicle
parent entity in Core Data that contains the shared properties, then making Vehicle
the parent entity of your other entities car, plane etc.
e.g.
You can then pass a Vehicle
managed object into your function like so:
func getDistanceTravelled(vehicle: Vehicle) -> Float {
return vehicle.distanceTraveled
}
This goes against the composite reuse principle mentioned above, but I think due to the nature of core data this could be one of those scenarios where inheritance wins.
A swifty solution is a protocol extension constrained to NSManagedObject
protocol TravelDistance {
var distanceTraveled: Float { get }
}
extension TravelDistance where Self : NSManagedObject {
func getDistanceTravelled(vehicle: TravelDistance) -> Float {
return vehicle.distanceTraveled
}
}
All NSManagedObject
subclasses which conform to TravelDistance
can use this method.