When using the variable all
in the Enum MotorVehicle
in order to pass all enum cases, the code does not compile. But doing the same thing witnout using said variable works. Why is this? I want to make the Enum "aware" of all its cases, not having to create arrays of it everywhere, or having to use "map". And using the solution with the variable allAsProtocol
(used by version 7) is just plain ugly IMHO. Any ideas?
Swift 2.2 code (just paste the code below in a Playground)
protocol Motorized {
func startEngine()
}
enum MotorVehicle: String, Motorized {
case Car
case MotorCycle
static var all: [MotorVehicle] {
return [.Car, .MotorCycle]
}
static var allAsProtocol: [Motorized] {
return [MotorVehicle.Car, MotorVehicle.MotorCycle]
}
func startEngine() {
print("Starting \(self.rawValue)")
}
}
func start(motorized motorized: [Motorized]) {
for motor in motorized {
start(motorized: motor)
}
}
func start(motorized motorized: Motorized) {
motorized.startEngine()
}
// VERSION 1
start(motorized: MotorVehicle.Car) //works
// VERSION 2
start(motorized: [MotorVehicle.Car, MotorVehicle.MotorCycle]) //works
// VERSION 3
/* In my opinion, this is logically identical to the code at the previous line... */
start(motorized: MotorVehicle.all) //Compilation Error - Cannot convert value of type ‘[MotorVehicle]’ to expected argument type ‘[Motorized]'
// VERSION 4
start(motorized: (MotorVehicle.all as! [Motorized])) //Compilation Error - 'Motorized' is not a subtype of 'MotorVehicle'
// VERSION 5
start(motorized: (MotorVehicle.all as [Motorized])) //Compilation Error - cannot convert value of type [MotorVehicle] to type [Motorized] in coercion
// VERSION 6
start(motorized: (MotorVehicle.all.map { return $0 as Motorized } )) //works
// VERSION 7
start(motorized: MotorVehicle.allAsProtocol) //works