[swift-evolution] [Review] SE-0026 Abstract classes and methods

Haravikk swift-evolution at haravikk.me
Thu Mar 10 04:54:04 CST 2016


> On 9 Mar 2016, at 20:35, Evan Maloney <emaloney at gilt.com> wrote:
> 
> On Mar 4, 2016, at 5:42 AM, Haravikk via swift-evolution <swift-evolution at swift.org> wrote:
> 
>> Someone asked in this discussion whether classes are second-class citizens in Swift, and thinking about it some more I kind of think that they are; after a period of adjustment I now use structs for almost everything. I only use classes where a common reference is absolutely necessary, and also for nested types.
> 
> It seems to me that you are using classes and structs in exactly the right way. However, I don't think your judicious use of classes is necessarily an argument that "classes are second-class citizens in Swift".
> 
> Sometimes classes are the right tool for the job. Sometimes structs or enums are.
> 
> What I love about Swift is that it's often much easier to use the right tool for the right job than other languages. However, if classes are relegated to some sort of demoted status, over time, that would no longer be the case.

Well, I may also be on the verge of changing my mind once again; I recently implemented an AnyFoo<T> type, however the boxing is a nightmare without support for abstract classes. Assuming I’m still doing it the right way, boxing a value for type erasure requires a base class FooBoxBase<T>, and a sub-class FooBox<F:Foo> (as FooBox is also of type FooBoxBase<T>, you don’t need to know what type F is within AnyFoo<T>). However, the type I’m boxing has a lot of methods, which means a huge amount of boiler-plate in FooBoxBase that just contains fatal errors, that in turn have to be overridden in FooBox.

With an abstract class this boiler-plate not only wouldn’t be necessary, but would also avoid mistakes such as my forgetting to override a method in FooBox (resulting in the fatal error super method being called instead).

Anyway, while I’m generally a convert to doing everything via protocols first, I think there are still cases where abstract is the best way, as mixins  and similar can't solve the boxing problem either. Of course we could get some syntactic sugar to make boxing easier (since it’s a very useful thing to do) but there may be similar cases where it just isn’t possible to do cleanly without proper abstract support.

P.S- I reserve the right to change my mind again in future =)


More information about the swift-evolution mailing list