[swift-users] Why can't structs inherit from other structs?
Rick Mann
rmann at latencyzero.com
Tue Aug 2 16:27:03 CDT 2016
> On Aug 2, 2016, at 07:48 , Karl <razielim at gmail.com> wrote:
>
>
>
>> * Structs have statically-dispatched methods and properties; there's no ability to override.
>>
>
> I wonder if that is an inherent property of structs, or a side-effect from them having no inheritance. There is no way to define something else which also “is” a CGRect, so all structs are final, and final is what gives static dispatch.
> If you access a struct via a protocol reference (PWT), you will get dynamic dispatch.
>
>> In my case, I have a rect-like value type, but I'd rather it inherit from CGRect, rather than contain a CGRect. That makes it much more natural to use.
>
> I’m reading this to mean you want something which “is” a CGRect. If we allowed those kinds of relationships for structs, and when using the open base type:
>
> - Methods would have to be dynamically dispatched unless declared final
> - Instance size would not be known, requiring heap allocation and storing pointers when used as a member
> - The sub-structs would lose information when bridged to their C equivalents. The CoreGraphics/UIKit framework code is not going to store and pass around your big CGRects
>
> The problem you are facing is a library limitation. CoreGraphics and UIKit do not allow you to abstract the concept of a “rect”. You could suggest that they replace CGRect with an extendable abstraction (i.e. an open class or a protocol) to represent a rectangle. Those libraries follow this pattern in other areas - for example, UITextPosition and UITextRange are abstract classes and intended to be subclassed. However, replacing CGRect would break lots of existing code and possibly introduce performance regressions, and the benefits are not likely to be significant enough to warrant it.
What I used to do in C++ was subclass CGRect. In this way, I could pass my rect to CoreGraphics methods directly, because the any reference to my subclass started with the same bytes as the CGRect, and everything worked (not withstanding that most of CG copies rects, rather than operating on references to them).
Maybe this particular use case is too limited or specialized, but I wish I could do the same thing in Swift.
--
Rick Mann
rmann at latencyzero.com
More information about the swift-users
mailing list