[swift-users] More questions about protocol/value programming
Rick Mann
rmann at latencyzero.com
Mon Aug 1 15:32:15 CDT 2016
In my schematic capture app, I had a class hierarchy that started with Element. From that I derived PartDefinition and PartInstance. Element has an immutable UUID, name, and description. Element knows how to encode itself as XML by conforming to an XMLCoding protocol.
Now I'm trying to make Element into a Protocol, and make PartDefinition and PartInstance into structs. But I can't quite figure out how to inherit the XMLCoding implementation for Element. That is, Element can encode/decode its UUID, name, and desc. It does the decode in a convenience init(xml:) method that takes an XMLNode to parse.
So how to I add another init(xml:) method to one of my structs (like PartDefinition), and have it call the init(xml:) method on Element? With class inheritance, I was able to do this with a call to super. It's not clear to me how to do this with Protocols.
It needs to be in init() because I want some of the instance variables to be let and non-optional. Not actually sure how to do this.
protocol Element
{
var uuid : UUID { get }
var name : String? { get }
var desc : String? { get }
}
extension Element
{
init(xml inElement: XMLElement)
{
self.uuid = <parse from inElement>
}
}
class
PartInstance : Element
{
init()
{
self.uuid = UUID()
}
init(xml inElement: XMLElement)
{
// Use shared implementation in Element extension?
}
let uuid: UUID
var name: String?
var desc: String?
}
class
PartDefinition : Element
{
etc...
}
I may be missing some aspect of this entirely, but I'm having a hard time seeing how to avoid lots of code duplication in this scenario. Appreciate thoughts and adviceā¦
--
Rick Mann
rmann at latencyzero.com
More information about the swift-users
mailing list