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

Mike Kluev mike.kluev at gmail.com
Thu Jun 22 16:28:24 CDT 2017

On Wed, 21 Jun 2017 15:04:46 David Moore <mooredev at me.com> wrote:

> This would be a bit counter-intutivie in my opinion, and it’s already
> with the language today. First of all, structs in Swift cannot be built
> Rather, I believe the intention is to use protocols for such a task.
That’s what
> the new Swift String and Substring structs do. The following code example
> demonstrates the intended behavior, without any additional language
> protocol Foo {
>     func a() -> Any?
> }
> extension Foo {
>     func a() -> Any? {
>         return nil
>     }
> }
> struct ValueSemantics: Foo {}
> class ReferenceSemantics: Foo {}

while you can use protocols, and protocol extensions specifically, to share
implementation there are two obvious problems with this "workaround":

1) protocol extensions' based implementation is very limited as you have no
storage around. e.g. start with a normal struct method that accesses an
instant variable and try to refactor it into a protocol extension... in
other words try doing anything useful other than "return nil" above,
anything that requires instance variable access. you'll have to be creative
in your protocol implementation, e.g. have a "var storage { get set }" as
part of the protocol and implement that "var storage" inside your struct
(and class), and in case of "struct" it would be strange as the struct
itself is (already) the storage, so you would introduce another level of
indirection for no good reason other than to satisfy this workaround, which
is not nice to begin with and has to be thought upfront (see below)

2) the proposed method works with value types that are already available
(e.g. the OS structs or third party ones) - something you can not change
but still want to wrap into a reference type.

this proposal is purely a syntactic sugar if you will... imagine a value
type "S" that you didn't create that has two hundred methods in it. of
course you can:

class C /* : S */ {

// implement manually:
  var `struct`: S

  // manually put two hundred pass through methods here...

  func method1() {
  // ...

it would be just painful. but the semantic of the proposed solution is
exactly the same, so any question "how it will do this" or "how it will
behave in regards to that" can be immediately answered by looking at the
equivalent "manual" implementation, so no hidden surprises here.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170623/fae0d8f4/attachment.html>

More information about the swift-evolution mailing list