【问题标题】:Alternate approach to inheritance for Swift structs?Swift 结构的替代继承方法?
【发布时间】:2018-02-16 04:10:23
【问题描述】:

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

【问题讨论】:

    标签: swift inheritance struct


    【解决方案1】:

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

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

    【讨论】:

    • 您不能通过协议扩展添加成员变量,这是非常有限的。
    • 可以添加静态方法(见代码)。此处示例:repl.it/repls/BleakYouthfulConstants
    • 非常聪明的方法!!
    【解决方案2】:

    遵循 Gist 有详细的答案,包括所有可能的方法。我不喜欢其中任何一个,因为我是 Classes 的粉丝。但是结构是 Swift 的未来,你必须理解、采用和喜欢 :( 它。

    链接: https://gist.github.com/AliSoftware/9e4946c8b6038572d678

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-02
      • 2023-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多