[swift-users] Why can't structs inherit from other structs?
Joe Groff
jgroff at apple.com
Tue Aug 2 17:10:27 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?
Class-style inheritance is tied to identity. Value types in Swift have no identity except for the value they contain, and they can be freely copied (or not) by the implementation. By adding fields to a struct, you change the value of that struct, and it doesn't make sense to say that a value with fewer fields "is-a" value with added fields. Those extra fields added by a sub-struct could be arbitrarily lost by copying (as often happens in C++ when copy constructors are invoked on inherited structs) and make defining equality difficult. Classes don't have these problems since each instance has a unique independent identity, and only references to that instance are passed around.
> 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?
There is a different kind of inheritance that may make sense for value types. You can consider a type that can represent a proper subset (or the same set) of values from another type to be its subtype; for example, UInt8 could be a subtype of UInt16. If you have another rect-like type, which represents rectangles in a different way (perhaps using integer coordinates instead of Double, or using coordinate ranges instead of base + size), it might make sense for us to allow you to treat it as a subtype of CGRect for convenience.
-Joe
More information about the swift-users
mailing list