簡體   English   中英

從以下示例中刪除冗余代碼

[英]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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM