An alternative approach to inheritance for Swift structures?

I use structs instead of classes to store data in my iOS application due to the obvious advantage of value vs. reference types However, I'm trying to figure out how to create groups of similar content. User messages may consist of images, text and / or names. If I used classes, then the approach I would use has a common class superclass Postwith different subclasses representing different types of messages. That way, I could transmit data Postand cite them if necessary. However, structures do not allow inheritance, so how can I create something like this?

+4
source share
1 answer

In Swift with a framework, you can create protocolfor a common task, as well as implement a default implementation using a 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
    }
}
+4
source

Source: https://habr.com/ru/post/1693717/


All Articles