What is the difference between global variable and shared instance in Swift? what are their respective field of use? Could anyone clarify their concept based upon Swift.
相关问题
- “Zero out” sensitive String data in Swift
- SwiftUI: UIImage (QRCode) does not load after call
- Get the NSRange for the visible text after scroll
- UIPanGestureRecognizer is not working in iOS 13
- What does a Firebase observer actually do?
相关文章
- Using if let syntax in switch statement
- Enum with associated value conforming to CaseItera
- Swift - hide pickerView after value selected
- Is there a Github markdown language identifier for
- How can I vertically align my status bar item text
- Adding TapGestureRecognizer to UILabel in Swift
- Attempt to present UIAlertController on View Contr
- Swift - Snapshotting a view that has not been rend
A global variable is a variable that is declared at the top level in a file. So if we had a class called
Bar
, you could store a reference to an instance ofBar
in a global variable like this:You would then be able to access the instance from anywhere, like this:
A shared instance, or singleton, looks like this:
Then you can access the shared instance, still from anywhere in the module, like this:
However, one of the most important differences between the two (apart from the fact that global variables are just generally discouraged) is that the singleton pattern restricts you from creating other instances of
Bar
. In the first example, you could just create more global variables:However, using a singleton (shared instance), the initialiser is private, so trying to do this...
...results in this:
That's a good thing, because the point of a singleton is that there is a single shared instance. Now the only way you can access an instance of
Bar
is throughBar.shared
. It's important to remember to add theprivate init()
in the class, and not add any other initialisers, though, or that won't any longer be enforced.If you want more information about this, there's a great article by KrakenDev here.
Singleton (sharing instance)
Ensure that only one instance of a singleton object is created & It's provide a globally accessible through shared instance of an object that could be shared even across an app. The dispatch_once function, which executes a block once and
only once for the lifetime of an app
.Global variable
Apple documentation says Global variables are variables that are defined
outside of any function, method, closure, or type context
.