As a fun project, I'm wanting to model an electronic circuit.
Components inherit from a superclass (ElectronicComponent). Each subclass (e.g. Resistor) has certain methods to return properties (e.g. resistance), but may vary by the number of outlets (lead
s) they have, and what they are named.
Each outlet connects to a Junction.
In my code to assemble a circuit, while I'm able to manually hook up the outlets to the junctions, I'd like to be able to use code similar to the following…
class Lead: Hashable // implementation omitted
{
let id = UUID()
unowned let component: ElectronicComponent
weak var connection: Junction?
init(component: ElectronicComponent, to connection: Junction? = nil)
{
self.component = component
self.connection = connection
}
}
@dynamicMemberLookup
class ElectronicComponent
{
let id = UUID()
var connections: Set<Lead> = []
let label: String?
init(label: String)
{
self.label = label
}
subscript<T>(dynamicMember keyPath: KeyPath<ElectronicComponent, T>) -> T
{
self[keyPath: keyPath]
}
func connect(lead: KeyPath<ElectronicComponent, Lead>, to junction: Junction)
{
let lead = self[keyPath: lead]
lead.connection = junction
connections.insert(lead)
}
}
class Resistor: ElectronicComponent
{
var input, output: Lead?
let resistance: Measurement<UnitElectricResistance>
init(_ label: String, resistance: Measurement<UnitElectricResistance>)
{
self.resistance = resistance
super.init(label: label)
}
}
let resistorA = Resistor("R1", resistance: .init(value: 100, unit: .ohms))
let junctionA = Junction(name: "A")
resistorA.connect(lead: \.outlet2, to: junctionA)
While I'm able to do this by implementing @dynamicMemberLookup
in each subclass, I'd like to be able to do this in the superclass to save repeating the code.
subscript<T>(dynamicMember keyPath: KeyPath<ElectronicComponent, T>) -> T
{
self[keyPath: keyPath]
}
Unfortunately, the compiler is not allowing me to do this as the superclass doesn't know about the subclass properties, and at the call site, the subclass isn't seen as ElectronicComponent
.
I've been doing trial and error with protocol conformance and other things, but hitting walls each time.
One possibility is replacing the set of outlets with a dictionary, and using Strings instead of key paths, but would prefer not to.
Another thing I haven't tried is creating and adopting a protocol with the method implemented in there. Another considered approach is using macros in the subclasses, but I'd like to see if there is a possibility of achieving the goal using my current approach, for learning as much as anything.
I’m gonna recommend that you ask this over in Swift Forums > Using Swift. This is a question about Swift the language, rather than anything Apple specific, and you’ll get more diverse opinions over on Swift Forums.
I’ll see you over there!
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"