[swift-users] Why can't structs inherit from other structs?
Karl
razielim at gmail.com
Tue Aug 2 09:48:45 CDT 2016
> * 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.
Karl
More information about the swift-users
mailing list