DevPrep

All topics › The Swift Language

Can you make a weak var for a struct? Why not?

Middle PRO

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

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store