Generics variable declaration in Swift -
i have created simple code in playground.
class carbrand { } class bmw: carbrand { } class mercedes: carbrand { } class car<t: carbrand> { } class employee { var car: car<t: carbrand>?// of cource doesn't work, idea there might car type } let employeeone = employee() employeeone.car = car<bmw>() let employeetwo = employee() employeetwo.car = car<mercedes>()
the simple question is: how declare variable generics when type not known @ compile time? seems swift requires have type defined , known makes generics useless in scenario.
this weird, class car should holds stored property "brand" of type carbrand rather using generic form. example:
class car { let brand: carbrand init(brand: carbrand) { self.brand = brand } } class employee { var car: car init(car: car) { self.car = car } } let employeeone = employee(car: car(brand: bmw())) let employeetwo = employee(car: car(brand: mercedes()))
btw, might better define carbrand
protocol.
Comments
Post a Comment