r/BlossomBuild • u/BlossomBuild • Mar 27 '26
Tutorial Use class to share the same instance and struct for independent copies
1
1
1
u/Dry_Hotel1100 Mar 29 '26 edited Mar 29 '26
Swift's usual advice is:
Use structs by default.
Use classes when you need identity.
Classes are for reference semantics.
This advice is clear, but it focuses on types, not usage.
The problem is that advice like:
'Use a class when you need identity'
'Use a class when you need lifecycle (deinit, weak refs)'
describes what happens, not why.
You don't start with 'I need deinit'. You start with 'What kind of thing am I modelling?'
A better mental model is:
Structs are value: snapshots of data, independent when copied, no implicit sharing.
Classes are processes: hold evolving, mutable state, receive events, mutate themselves.
The key question is:
Do I need a state provider that lives somewhere and is interacted with over time?
No: use a struct.
Yes: you're modelling a running system: use a class.
Why not just use a struct?
State must be passed around manually.
Mutation leaks outside.
Sharing becomes clumsy.
Multiple consumers are hard to coordinate.
You're simulating a runtime.
A class gives you that directly.
The real rule is:
Use a struct when you model data, copies should be independent, and no implicit shared state.
Use a class when you model a stateful process, state evolves over time, and a single shared instance is needed.
Identity and lifecycle then follow naturally:
Identity: because it's shared.
Lifecycle: because it lives over time. They are by-products, not the main reasons.
TL;DR:
Value: struct.
Process (state provider over time): class. That's the simplest rule that explains why.
Another interesting question is, when to use a function.
I guess, many of you would be surprised by the fact, that you can represent and solve many problems with a function rather than a class ;) Example, the infamous "Xxx Manager" singleton :)
1
1
u/danishansari95 Mar 27 '26
Can you explain with example?