class Car {
//....
}
class ElectricCar : Car {
//...
}
We have a small database of cars:
var cars = [Car(), Car(), ElectricCar(), ElectricCar(), Car()]
And one function that is returning one electric car:
for car in cars {
if car is ElectricCar {
return car
}
}
return nil
}
In our code, in multiple places we have to downcast the objects from Car to ElectricCar:
electricCar1 = findElectricCar() as! ElectricCar
electricCar2 = findElectricCar() as! ElectricCar
electricCar3 = findElectricCar() as! ElectricCar
To improve the code, we need to move the casting directly into the function
func findElectricCar() -> ElectricCar? {
for car in cars {
if car is ElectricCar {
return (car as! ElectricCar)
}
}
return nil
}
Now our code looks more elegant:
var electricCar1, electricCar2, electricCar3: ElectricCar
electricCar1 = findElectricCar()
electricCar2 = findElectricCar()
electricCar3 = findElectricCar()
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.