2

I'm still confused a little with using Swift and was hoping that someone could help clarify when and why I would you them. From my understanding of Singleton's they are single class entities, meaning that if I have Class A and I create a shared instance of Class A in a Class B its just a reference to Class A in B, so if I change or modify the object that references Class A in Class B, the original object Class is is not effected, only the object in Class B is.

What if I wanted to have a Class A, and Class B, and in Class B create a direct reference to Class A, so any changes I make are effected in class A going forward. The class is directly modified not the instance of the object that references that class.

2
  • Singleton is a pattern design where a class can be instanced only once in all your context, app etc, so your object instance is the same Commented Aug 5, 2016 at 16:14
  • A singleton is a global instance of a class that is accessible from anywhere in the application. When changes occur to that instance in one place it also changes for everything else that wants access. Commented Aug 5, 2016 at 16:14

1 Answer 1

17

Singleton

Look at this singleton class

final class Singleton {
    static let sharedInstance = Singleton()
    private init() { }

    var value = 0
}

How does it work

There is NO WAY (outside of the source file where it is defined) to create more than 1 instance of this class because the initializer has been marked private.

The only way to access an instance of Singleton is using sharedInstance which does return the only instance available.

You can invoke sharedInstance as many times as you want, from any class and then copy it as long as you want. Every variable will always contains a reference to the only instance of Singleton allocated on the Heap.

So every change you do to sharedInstance will be shared everywhere.

enter image description here

Example

let a = Singleton.sharedInstance
a.value = 1

let b = Singleton.sharedInstance
print(b.value) // 1
b.value = 2

print(a.value) // 2
Sign up to request clarification or add additional context in comments.

4 Comments

It is imperative that the Singleton class be marked as final, otherwise we can use subclassing and to-parent casting to create several Singleton instances (hence invalidating the "There is NO WAY (outside of the source file where it is defined) to create more than 1 instance ..." statement above), see e.g. this example. Even if such workarounds are obviously bad practice, marking the Singleton as final removes the possibility of doing so.
I'd like to know about that graphic, too
@AlexanderMomchliov: Hi, the software is Graphic
@appzYourLife It's pretty :) have an upboat.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.