I just wanted a refresher - struts versus properties.


Alex Zavatone
 

We’ve all seen so many Swift references about when to use a struct as opposed to a class. But coming from Objective-C like lots of us, does anyone have any resources or guidelines for when and why to use structs over @properties?

It seems that there are very few guidelines on this front, making it pretty vague when when actually looking for reasons why we should choose one over the other.

The “just because it’s Swift” approach that people often go with sure isn’t a sensible reason.

Thanks in advance.
Alex Zavatone


Ben Kennedy
 

On 21 Apr 2022, at 9:03 am, Alex Zavatone via groups.io <zav@...> wrote:

But coming from Objective-C like lots of us, does anyone have any resources or guidelines for when and why to use structs over @properties?
Properties can be structs just as much as they can be classes or other types.

It seems that there are very few guidelines on this front, making it pretty vague when when actually looking for reasons why we should choose one over the other.
Structs are value types, and classes are reference types. That's the biggest difference.

Does the model represent something that can meaningfully exist in duplicate, and be copied? Sounds like the job for a struct. Or does it represent something that has an identity, whose instances are semantically unique? Sounds like a class.

More generally, a rubric might be: does it need to be a class? Make it a class. If not, make it a struct.

-ben