Recommended way to refactor/combine multiple near-identical classes using Swift?

Viewed 104

In Swift, how would I combine the following into one class?

class FirstClass: Codable, ObservableObject {
  @Published var int: Int
  @Published var bool: Bool
  @Published var firstObject: FirstType

// plus inits and custom decoding/encoding stuff

}

class SecondClass: Codable, ObservableObject {
  @Published var int: Int
  @Published var bool: Bool
  @Published var secondObject: SecondType

// plus inits and custom decoding/encoding stuff

}

class ThirdClass: Codable, ObservableObject {
  @Published var int: Int
  @Published var bool: Bool
  @Published var thirdObject: ThirdType

// plus inits and custom decoding/encoding stuff

}

(with FirstType, SecondType and ThirdType also being class models that conform to Codable and ObservableObject)

in order to end up with something like this:

class CommonClass: Codable, ObservableObject {
  @Published var int: Int
  @Published var bool: Bool
  @Published var object: CommonType // which could accept FirstType, SecondType or ThirdType

// plus inits and custom decoding/encoding stuff

}

How should I go about doing this? And is there a better way that still works the way I intend?

I'm basically trying to achieve 2 things: 1-avoid repeating code (as in my real-life scenario there are a lot more variables in common than just an int and a bool) and 2-Make downstream code more straightforward by hopefully also minimising the need for separate views.

1 Answers

It is not clear about other code, but for that provided I would use generics, like

class CommonClass<T>: Codable, ObservableObject {
//class CommonClass<T: CommonType>: Codable, ObservableObject { // << as variant
  @Published var int: Int
  @Published var bool: Bool
  @Published var object: T

// plus inits and custom decoding/encoding stuff

}
Related