Swift结构的替代继承方法? [英] Alternate approach to inheritance for Swift structs?

查看:118
本文介绍了Swift结构的替代继承方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用结构而不是类将数据存储在我的i​​OS应用中,因为值与引用类型相比具有明显的优势.但是,我试图弄清楚如何构造相似内容的组.用户帖子可能包含图片,文字和/或标题.如果我使用的是类,我将使用的方法是使用一个通用的Post超类,该超类具有代表不同类型帖子的不同子类.这样,我就可以传递Post数据并根据需要进行转换.但是,结构不允许继承,那么如何构造类似的东西?

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?

推荐答案

在带有struct的Swift中,您可以为常见任务创建protocol,还可以使用协议扩展来实现默认实现.

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
    }
}

这篇关于Swift结构的替代继承方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆