[swift-users] Why can't structs inherit from other structs?

davelist at mac.com davelist at mac.com
Mon Aug 1 20:41:19 CDT 2016

> On Aug 1, 2016, at 8:28 PM, Rick Mann via swift-users <swift-users at swift.org> wrote:
> It sure seems natural.
> Is there some reason the language can't allow a sub-struct to add member variables, such that the whole is treated like a contiguous set of members?
> 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.
> Is allowing that just too complicated, or does it create type safety issues?
> -- 
> Rick Mann
> rmann at latencyzero.com

Inheritance isn't really compatible with value types at least if they're allocated on a stack (known as "stack-dynamic) and take a fixed amount of space (think about what would happen if you assigned it to a subclass that had additional data - no room to store the additional data). References are typically stored on a heap with a pointer to the object stored on a stack (pointers takes the same amount of memory no matter what type they point to). 

If you don't need extra data (additional instance variables), you can add new methods to CGRect using extensions.

Dave Reed

More information about the swift-users mailing list