Hacker News new | ask | show | jobs
by jayrhynas 3926 days ago
Wouldn't you define gas() and whatever class-specific methods in the class itself, instead of in extensions on the protocol?

    class SunnyRobot : Robot {
      func gas() { ... }
      func findSun() { ... }
    }
1 comments

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.

[1]: https://gist.github.com/jayrhynas/49945331e41314fc3ede

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.