简体   繁体   中英

Remove the redundant code from the following example

I have 3 structures:

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) . 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:

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.

Check this for more info https://www.appcoda.com/protocols-in-swift/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM