我有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
}
我有一个带有函数UITableViewCell
的{{1}}子类。我正在传递这三个结构的实例并配置单元。
我做了类似的事情
configure(_ object: Any)
但是我对这种方法导致的冗余代码不满意。您能建议我一种删除此冗余代码的方法吗?
答案 0 :(得分:4)
您可以制定协议
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
然后您更新:
fun configure(_ object: ProtocolName)
这将使结构符合协议。然后在configure中,您将可以访问协议中声明的vars的子集而无需强制转换。
选中此项以获取更多信息https://www.appcoda.com/protocols-in-swift/