Home > Mobile >  Swift: how to prevent duplicating code in two struct initializers conforming to the same protocol?
Swift: how to prevent duplicating code in two struct initializers conforming to the same protocol?

Time:10-22

I have a protocol that defines a simple dictionary:

protocol P {
    var dictionary: [String: Any] { get }
}

And two structs conforming to it:

struct S1: P {
    var moreInfo: [String]
    var dictionary: [String: Any]
}

struct S2: P {
    var dictionary: [String: Any]
}     

I want to initialize these structs from a given object, so the initializer would be something like this:

init(from data: [[String: Any]]) {
    dictionary = process(data)
    // Specifically in S1
    moreInfo = moreInfoProcess(data)
}

What is the best solution to prevent duplicating the same code in S1 and S2 to process data and setting dictionary ?

Thank you for your help

CodePudding user response:

The easiest way is to implement the common code in an extension to P (and make it static to avoid compilation errors)

extension P {
    static func process(_ data: [[String: Any]]) -> [String: Any] {
        var result = [String: Any]()
        // processing code...
        return result
    }
}
  • Related