Swift dynamicType does not work with generic function -
say have protocol:
protocol vehiclemodel {...}
it implemented number of different structs. (e.g. carmodel, truckmodel, etc.) have generic method vehicle's 'model identifier'.
func modelidentifierforvehicle<v: vehiclemodel>(vehicletype: v.type) -> string { return "\(vehicletype)" }
if call modelidentifierforvehicle(carmodel.self) returns "car" fine. if have polymorphic collections of vehiclemodel's , try call modelidentifierforvehicle(model.dynamictype) on each of them, xcode says "cannot invoke 'modelidentifierforvehicle' argument list of type (vehiclemodel.type)" why this? , how can work around it?
since you're converting vehicletype
string
in modelidentifierforvehicle
, argue why need use constrain v
vehiclemodel
, or use generics @ all:
func typeidentifier(t: any.type) -> string { return "\(t)" } let vehicles: [vehiclemodel.type] = [carmodel.self, truckmodel.self] typeidentifier(vehicles[0]) // carmodel
if there's reason need use vehiclemodel
, assuming vehiclemodel
doesn't use self
or associated type requirements, do:
func modelidentifierforvehicle(vehicletype: vehiclemodel.type) -> string { return "\(vehicletype)" }
if you're using swift 2, instead use protocol extension:
extension vehiclemodel { static var modelidentifier: string { return "\(self.dynamictype)" } } // array earlier. vehicles[1].modelidentifier // truckmodel.type
Comments
Post a Comment