Skip to content

Using structs instead of classes? #10

@derwaldgeist

Description

@derwaldgeist

Hi, I came along this interesting repo, as I was looking for the best way to implement a singleton pattern in Swift. As Swift also supports static properties (called Type properties in the Apple documentation) for structs, I'm just wondering if this would be an even better solution? The advantage I'm seeing is that structs - as opposed to classes - also allow to define static variables directly, so there is no need to define a constant like "sharedInstance", the struct itself could serve for this purpose. And as long as you don't define any non-static members, it would still be a singleton. Or am I missing something here?

EDIT: I think I can answer myself: The struct approach would not allow to pass the struct over in method calls, as it is possible with the .sharedInstance singleton instance of the class. And if a shared instance of the struct would be created, it would be handed over as a value type, hence effectively copying it instead of referencing it. Am I right?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions