trait Robot
var serialCode = generateSerialCode()
def gas
def engine = Engine(gas)
def body = Body(engine)
class SunnyRobot extends Robot
def gas = sun
class OilyRobot extends Robot
def gas = oil
Protocol extensions don't hold state. They are meant to provide default implementations for a type, not as a 1:1 relationship with the class it's implementing functionality for. Following what you're saying, I would be doing something like this:
That looks all good and well, right? Ok, well now my sunny robot wants to find the sun and my oily robot wants to go find oil. How to provide functionality unique to each of them? Maybe I'm just not getting something, but I'm pretty sure protocol extensions are not the answer to the problem I'm trying to describe.
When you're working in front-end land, you can do your best to stay functional and be cool and all that jazz, but it's just a waste of time usually. You're going to use a lot of state and you just have to learn how to manage that effectively (IMO). What this boils down to for me is that I might build a cell that does 3 things great and will be on every cell, but then business designs call for 2 slightly different cells still based upon that main cell. Oh and when those different cells are tapped, different things should happen.
So again, I just go about doing it with the simple base class gonna throw you an exception unless you override the "abstract" method. This way, I get to keep state going down and classes can actually fill up naturally rather than playing the protocol game.
By defining `gas()` in the children, you can't take advantage of it in base class. For example, the base robot might know how to move and all that, but the sunny robot just needs to know where it's going.
Protocol extensions just don't cut it, I'm sorry. They're great for defining some default behavior and doing kinda-abstract-classes, but it's a different playing field in Swift/Obj-C than Java/Scala/C#/etc..
I think this[1] does what you want, unless I'm not understanding your problem description. AFAIK you are correct about protocol extensions not holding state. So I don't think you can implement the `var serialCode = generateSerialCode()` with just a protocol. But you could do it with a protocol + base class.
Edit: I just realized that with this method, the protocol extension is useless, you could just define `move` on Robot. So protocol extensions can give you a mix of abstract & default methods but if you need to inherit state you need to use a base class.