I have 2 types, A
and B
that implement the same methods and have the same properties on them. I have defined an extension to fetch a value in a sub property for each of A
and B
. I want to know if there is a way to reduce those 2 extensions down to 1 method. Imagine there are many more types like A
and B
so the code duplication problem becomes much worse.
Update: A
and B
are generated along with many others like them. The original plan is to avoid writing extensions at all for A
or B
. I don't know if this is possible but I was told I could use KeyPaths for this. The properties names must be different. This is a byproduct of the code generation
struct A {
var something: Common
}
struct B {
var somethingElse: Common
}
struct Common {
var value1: String
var value2: String
}
extension A {
func valueFor(condition: Bool) -> String {
return condition ? self.something.value1 : self.something.value2
}
}
extension B {
func valueFor(condition: Bool) -> String {
return condition ? self.somethingElse.value1 : self.somethingElse.value2
}
}
I think protocols are the solution for your problem. They help to make code more generic.