Can you make a weak var for a struct? Why not?
The idea
No — a weak reference to a struct does not exist. weak and unowned are built on ARC: they point to a heap object that has a reference count, and weak is zeroed when the object is destroyed. A struct is a value type: it is copied in full, has no reference count and no shared instance to refer to "weakly". No object — nothing to zero out.
final class Session {}
protocol Delegate: AnyObject {} // class-bound: weak is allowed
struct ViewState {
weak var session: Session? // ok: weak ref to a class in a struct
weak var delegate: (any Delegate)?
}
// weak var state: ViewState? // error: 'weak' may only be applied to
// // class and class-bound protocol types
The rest of this answer, with code and interview follow-ups, is in the DevPrep app.
Read the full answer in DevPrep