-
Notifications
You must be signed in to change notification settings - Fork 101
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Using structs instead of classes? #10
Comments
I think that you basically got it right: Structs are value types, Classes are reference types in Swift. This leads to several disadvantages in general Singleton usage when using a struct, therefore a class should be the way to go. There might be some cases where it might even make sense to use a struct though. But these are not the common Singleton usage cases afaik. |
I came across this repo from Stack overflow and also found a link to the official Apple docs on creating singletons. |
@metalrecker: Thank you for pointing that out but I don't really understand what you want to say with this within this issue. Maybe you want to show that even Apple themselves use classes instead of structs? |
@hpique: This issue seems to be solved to me. Close? |
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?
The text was updated successfully, but these errors were encountered: