[swift-evolution] ability to derive a class from a struct or other value type

Tony Allevato tony.allevato at gmail.com
Fri Jun 23 15:18:44 CDT 2017

On Fri, Jun 23, 2017 at 10:28 AM Mike Kluev <mike.kluev at gmail.com> wrote:

> On 23 June 2017 at 18:31, Tony Allevato <tony.allevato at gmail.com> wrote:
>> Imagine something like this:
>> struct BaseStruct { ... }
>> class ExtendsStruct: BaseStruct { ... }
>> func foo(x: BaseStruct) { ... }
>> func bar(x: inout BaseStruct) { ... }
>> var x = ExtendsStruct(...)
>> foo(x)
>> bar(&x)
> would be:
> foo(x) // same as foo(x.super)  for which it easy to see what's going on
> bar(&x) // same as bar(&x.super) for which it is easy to see what's going
> on
>> What is the behavior in each of these cases? Do foo and bar get a
>> value-type slice of x? Is that slice the same memory as is occupied by x,
>> or is it a copy? When bar mutates its argument, does it modify the same
>> memory occupied by x?
> all these questions are easily answered if you consider the equivalent
> manual implementation...

No, they aren't, because the equivalent manual implementation that uses
composition does not permit you to pass an ExtendsStruct to a function that
expects a BaseStruct because they're different types.

Looking back, I must have missed your earlier message where you said that
`C() is S` would be false and you wouldn't be able to pass C where S is
required. Sorry about that. But if that's true, then you don't *really*
have an inheritance relationship at all. An inheritance relationship
specifically *does* mean that `C() is S` if C extends S. If your proposal
doesn't require that, then you effectively have composition that looks
syntactically like inheritance, and now you have an inconsistency in the

class C1: C2  ==>  C1() is C2 == true
class C1: P  ==>  C1() is P == true
class C1: S  ==>  C1() is S == false?

Given those statements, I think what you're asking for could be achieved
just as well using protocol forwarding, which makes the composition
relationship explicitly visible instead of hiding it in something that it's

>> Let's go back to step 1: what's your use case for wanting inheritance
>> between a class and a struct vs. something like protocol forwarding?
> i don't control the preexisting value type in general case, so there is no
> protocol around to hijack.
> essentially this proposal allows your own or preexisting value type to act
> as a reference type without having any code or upfront provisions. no more,
> no less. if you ever had a thought similar to: "i need String / Data / Rect
> / etc but the one that's reference type" this device will be for you.
> class ClassString: String {}
> class ClassData: Data {}
> class ClassCGRect: CGRect {}
> Mike
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170623/ddb1fcb0/attachment.html>

More information about the swift-evolution mailing list