Alternate approach to inheritance for Swift structs?
In Swift with struct you can create protocol
for common task and also implement default implementation using protocol extension.
protocol Vehicle { var model: String { get set } var color: String { get set }}//Common Implementation using protocol extensionextension Vehicle { static func parseVehicleFields(jsonDict: [String:Any]) -> (String, String) { let model = jsonDict["model"] as! String let color = jsonDict["color"] as! String return (model, color) }}struct Car : Vehicle { var model:String var color:String let horsepower: Double let license_plate: String init(jsonDict: [String:Any]) { (model, color) = Car.parseVehicleFields(jsonDict: jsonDict) horsepower = jsonDict["horsepower"] as! Double license_plate = jsonDict["license_plate"] as! String }}struct Bicycle : Vehicle { var model:String var color:String let chainrings: Int let sprockets: Int init(jsonDict: [String:Any]) { (model, color) = Bicycle.parseVehicleFields(jsonDict: jsonDict) chainrings = jsonDict["chainrings"] as! Int sprockets = jsonDict["sprockets"] as! Int }}
There is a detailed answer at following Gist, with all possible approaches. I do not like any of them as I am fan of Classes. But structs are future of Swift, you have to understand, adopt and like :( it .
Link: https://gist.github.com/AliSoftware/9e4946c8b6038572d678