[swift-users] Why can't structs inherit from other structs?
brent at architechies.com
Tue Aug 2 03:24:21 CDT 2016
> On Aug 1, 2016, at 5: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?
Structs are very "raw":
* There is no extra overhead for metadata; objects have a header which includes a type reference, a reference count, and various other housekeeping bits.
* Structs have a fixed size; there's no space for additional fields.
* Structs have statically-dispatched methods and properties; there's no ability to override.
This makes them small and fast, which are necessities if we're to use them to implement fundamental data types like `Int`. Basically, if structs weren't already so "primitive",
> 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.
Keep in mind that you have three options—not just one—if you want to increase the capabilities of a struct:
1. Composition, as you seem to have already evaluated.
2. Extensions to add extra methods or computed properties to an existing struct.
3. Protocols and retroactive modeling if you want to be able to handle instances of both types with a single piece of code.
You don't mention what it is you want to do, but it's possible that one of these will address your needs.
More information about the swift-users