Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternate approach to inheritance for Swift structs?

I'm using structs instead of classes to store data in my iOS app because of the obvious advantage of value vs reference types. However, I'm trying to figure out how to architect groups of similar content. User posts may consist of images, text, and/or titles. If I were using classes the approach I would use is having a common Post superclass with different subclasses representing different types of posts. That way I could pass Post data around and cast as needed. However, structs don't allow for inheritance, so how could I architect something similar?

like image 955
A Tyshka Avatar asked Feb 16 '18 04:02

A Tyshka


People also ask

Can structs be inherited Swift?

Structs cannot have inheritance, so have only one type. If you point two variables at the same struct, they have their own independent copy of the data.

Can you subclass a struct Swift?

It is not possible to subclass a struct in Swift, only classes can be subclassed. An extension is not a subclass, it's just adding additional functionality on to the existing struct , this is comparable to a category in Objective-C.

Can structs inherit protocols?

Structures and protocols can only adopt protocols; they can't inherit from classes.


1 Answers

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 extension extension 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     } } 
like image 110
technerd Avatar answered Oct 11 '22 21:10

technerd