I believe vale is correct, that one would generally consider protocols in this case. In addition to providing the protocol definition for the requestKey
, I'd also implement request
as a default implementation of the protocol:
// define Furniture protocol
protocol Furniture {
static var requestKey: String { get }
static func request()
}
// implement default implementation in extension
extension Furniture {
static func request() {
print("class key => \(self.requestKey)")
}
}
// both Chair and Table conform to this protocol
class Chair: Furniture {
static let requestKey = "jsonchairs"
}
class Table: Furniture {
static let requestKey = "tables"
}
Note, I'm assuming that the Furniture
base class was not really needed, so I co-opted that for my protocol. You just need to decide whether you really need this Furniture
base class or not. My rule of thumb as I've transitioned from object-oriented to protocol-oriented programming is whether there can be concrete instances of this Furniture
type, or whether it's more of an abstract/virtual type that is used merely to define some shared behavior of other types that will ultimately be instantiated (i.e. Chair
and Table
types).
If Furniture
truly is a concrete type, then you'll have to find a way to achieve what you want without using static
types or methods because you cannot override statics. If you show us how you're using this Furniture
type in addition to the Chair
and Table
types, we might be able to help you refactor this in such a manner that you won't need the static
methods/types.
But if Furniture
is not a concrete type, then I'd suggest pushing yourself and see whether you can accomplish everything you need with a protocol. When you make the shift from object-oriented programming to protocol-oriented programming, it takes a little time to grok it. Just don't be too Crusty. For more information, see WWDC 2015 video Protocol-Oriented Programming in Swift or the equivalent WWDC 2016 video Protocol and Value Oriented Programming in UIKit Apps.
As an aside, even if you adopt this protocol-oriented pattern, I wouldn't be inclined to use static
types/methods in your particular example, but that's a separate question. The above protocol-oriented pattern works equally well for static
methods as it does for instance methods.