Structures that wrap classes should conform to AnyObject

Consider the following code:

class Foo { }

struct Bar {
    let foo: Foo
}

struct Baz {
    let bar: Bar
}

Bar and Baz should both conform to AnyObject. They could then be used with Unmanaged, which would be very useful. Bar and Baz should also receive the same optimization that classes do when they are the sole capture of an escaping closure (use the object reference itself as the context pointer, avoiding a new allocation).

To avoid also affecting value types like Array, this feature could be opt-in via an explicit conformance:

class Foo { }

struct Bar: AnyObject {
    let foo: Foo
}

struct Baz: AnyObject {
    let bar: Bar
}

Wrapping classes in structures is a great way to change an object's interface; these wrappers shouldn't lose the special capabilities that bare classes have.

Why should they conform to AnyObject? For what reasons or purposes? The motivation is not clear.
Array has value semantics and the underlying internal ref buffer is an implementation detail. These wrappers do not implement cow and differ a lot from Array, so parrallel between these wrappers and Array is also unclear.

Class have inheritance and @objc capabilities e.g. I could hardly imagine them for a struct. If you want structs to have these capabilities then you probably want a class.
I suppose it would be better to talk a bit about task you want to solve this way at first.

6 Likes

Actors and classes can also be used for making a facade for underlying object. Do you have specific constraints making both of them unsuitable?

I recommend that you read my post again; respectfully, you comprehended it poorly.

For more motivation, recognize that a structure that wraps a class has equivalent memory layout to a class, and AnyObject is little more than a layout constraint.

A better motivational example is needed that shows the benefit of the proposed feature compared to using a bare baz.bar.foo when a reference is needed and using Baz(bar: Bar(foo: foo)) to make a struct from a reference.

5 Likes

As others have said; a more comprehensive motivation is needed to fully understand the rational behind this pitch,

2 Likes

That is just implementation details, and cannot be the reason to change language logic. I believe that logic is

  • Any can be used for values of both value and reference types.
  • AnyObject can be used for values of reference types only, i.e. class types.
2 Likes