class Car and Truck are written here as an example but they could be unknown to the program at compile time.
there could be more kinds of cars not yet known
for instance there could be a special class called Ferrari, Lamborghini, that may come down the road not known to the system.
our objective is to program to interface, not to a specific implemenation
we need to do similar to the following
- create an instance
var vehicle: IDrive = Vehicle()
vehicle.drive()
we tried some techniques and couldn't get it working without casting to specific implementations, need an independent solution without a need to cast to a specific implementation.
Any lateral approach also welcome, maybe our approach is totally wrong but keeping in mind the constraints that function instantiateAndDrive
has to have a protocol
based parameter
Note to negative voters aka dummies: instead ask questions to clarify if it doesn't make sense to you or go get yourself a "Design Pattern Book for Idiots"
public protocol IDrive {
func drive()
}
public class Car: IDrive {
public init() {}
public func drive() {}
}
class Truck: IDrive {
public init() {}
public func drive() {}
}
class Test { //our attempts
func instantiateAndDrive(Vehicle:IDrive.Type) {
var vehicle = Vehicle()
vehicle.drive()
}
func instantiateAndDrive2<T:IDrive>(Vehicle: T) {
var vehicle = Vehicle()
vehicle.drive()
}
}
var test = Test()
test.instantiateAndDrive(Car.self)
Edit - Attempt using class after AirSpeed Velocity's Answer
public protocol Drivable {
init()
func drive()
}
public class Car: Drivable {
public required init() {}
public func drive() { println("vroom") }
}
public class Truck: Drivable {
public required init() {}
public func drive() { println("brrrrrrm") }
}
class Test {
func instantiateAndDrive(Vehicle:Drivable.Type) {
var vehicle = Vehicle()
vehicle.drive()
}
func instantiateAndDrive2<T:Drivable>(Vehicle: T) {
ver vehicle = Vehicle()
vehicle.drive()
}
}
//var test = Test()
//test.instantiateAndDrive(Car.self)
//test.instantiateAndDrive(Truck.self)