从以下示例中删除冗余代码

Remove the redundant code from the following example

我有 3 个结构:

struct A: Decodable {
    var color: UIColor? = nil
    var version: String? = nil
    // and few specific to struct A
}

struct B: Decodable {
    var color: UIColor? = nil
    var version: String? = nil
    // and few specific to struct B
}
    
struct C: Decodable {
    var color: UIColor? = nil
    var version: String? = nil
    // and few specific to struct C
}

我有一个带有函数 configure(_ object: Any)UITableViewCell 子类。我正在传递这三个结构的实例并配置单元格。

我做了类似的事情:

func configure(_ object: Any) {
    if let aStruct = object as? A {
        view.color = aStruct.color
        label.text = aStruct.version
    } else if let bStruct = object as? B {
        view.color = aStruct.color
        label.text = aStruct.version
    } else if let cStruct = object as? C {
        view.color = aStruct.color
        label.text = aStruct.version
    }
}

但我对这种方法不满意,因为它会导致冗余代码。你能建议我一种删除这些冗余代码的方法吗?

你可以制定协议

protocol ProtocolName {
    var color: UIColor? { get set }
    var version: String? { get set }
}

然后你让A、B、C都遵守这个协议:

struct A: Decodable, ProtocolName
struct B: Decodable, ProtocolName
struct C: Decodable, ProtocolName

然后你更新:

func configure(_ object: ProtocolName)

这将使结构符合协议。然后在配置中,您将能够访问在协议中声明的 vars 的子集而无需强制转换。

查看此以获取更多信息https://www.appcoda.com/protocols-in-swift/