DevPrep

All topics › Memory management

Can a reference type live on the stack?

Senior PRO

Answer

Yes. A class instance is allocated on the heap by default (swift_allocObject), but the optimizer can place it on the stack if it proves the reference never leaves the function. The deciding condition is not "fixed size" (a class's size is always known) but escape analysis: the object is not stored in a field, not returned, not captured by an escaping closure, not passed to opaque code that could retain it.

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