Skip to content
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

Open
derwaldgeist opened this issue Aug 12, 2015 · 4 comments
Open

Using structs instead of classes? #10

derwaldgeist opened this issue Aug 12, 2015 · 4 comments

Comments

@derwaldgeist
Copy link

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?

@Jeehut
Copy link
Contributor

Jeehut commented Aug 12, 2015

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.

@ghost
Copy link

ghost commented Aug 24, 2015

I came across this repo from Stack overflow and also found a link to the official Apple docs on creating singletons.
https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/AdoptingCocoaDesignPatterns.html#singleton

@Jeehut
Copy link
Contributor

Jeehut commented Aug 24, 2015

@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?

@Jeehut
Copy link
Contributor

Jeehut commented Aug 24, 2015

@hpique: This issue seems to be solved to me. Close?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants