[英]Remove the redundant code from the following example
I have 3 structures:我有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
}
I have a UITableViewCell
subclass with a function configure(_ object: Any)
.我有一个带有函数
configure(_ object: Any)
的UITableViewCell
子类。 I am passing the instance of those three struct and configuring the cell.我正在传递这三个结构的实例并配置单元格。
I did something like:我做了类似的事情:
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
}
}
But I am not satisfied with this approach as it's leading to redundant code.但我对这种方法不满意,因为它会导致冗余代码。 Can you suggest me an approach that will remove this redundant code?
你能建议我一种删除这些冗余代码的方法吗?
You can make a protocol你可以做一个协议
protocol ProtocolName {
var color: UIColor? { get set }
var version: String? { get set }
}
Then you make A, B and C conform to this protocol:然后你让 A、B 和 C 遵守这个协议:
struct A: Decodable, ProtocolName
struct B: Decodable, ProtocolName
struct C: Decodable, ProtocolName
Then you update:然后你更新:
func configure(_ object: ProtocolName)
This will make structs conform to a protocol.这将使结构符合协议。 Then in configure you will be able access subset of vars declared in a protocol without casting.
然后在配置中,您将能够访问在协议中声明的 vars 的子集而无需强制转换。
Check this for more info https://www.appcoda.com/protocols-in-swift/检查此以获取更多信息https://www.appcoda.com/protocols-in-swift/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.