What's a singleton?

I read about it here but I even don't know what it is?


And what's the problem if I use a global variable?


Is it a way to save variables with

let defaults = UserDefaults.standard

defaults.set("Hello World", forKey: "BeginningText")

defaults.synchronize()


so that every class can access to it?



Can someone please answer this questions?


Would be very kind!

Accepted Reply

singleton (a pretty special *****) are to make sure instance is created only once.


I frequently use it to store globals, in a class and not as individual var.


The patern is:

class Global {
 
    class var shared : Global {
        struct Singleton {
            static let instance = Global()
        }
        return Singleton.instance;
    }                          
 
    var aProperty: String?

func setProperty(with s: String) {
     aProperty = s
}


Then, I use as follows


let x = Global.shared.aProperty


It is often good to create func to set values and use as:


Global.shared.setProperty("Some text")



Can read this to get more insight:

h ttps://cocoacasts.com/what-is-a-singleton-and-how-to-create-one-in-swift

Replies

singleton (a pretty special *****) are to make sure instance is created only once.


I frequently use it to store globals, in a class and not as individual var.


The patern is:

class Global {
 
    class var shared : Global {
        struct Singleton {
            static let instance = Global()
        }
        return Singleton.instance;
    }                          
 
    var aProperty: String?

func setProperty(with s: String) {
     aProperty = s
}


Then, I use as follows


let x = Global.shared.aProperty


It is often good to create func to set values and use as:


Global.shared.setProperty("Some text")



Can read this to get more insight:

h ttps://cocoacasts.com/what-is-a-singleton-and-how-to-create-one-in-swift

Thank you for your answer, Claude!

Hello Claude,


I'm confused about this issue:

As soon as I make more than one variable in your example I get these bad errors:

class Global {     Class 'Global' has no initializers
    
    class var shared : Global {
        struct Singleton {
            static let instance = Global()    'Global' cannot be constructed because it has no accessible initializers
        }
        return Singleton.instance;
    }
    
    var aProperty: String?
    var text: [String?]
    
    func setProperty(with s: String) {
        aProperty = s
    }
    func setText(with s: [String]) {
        text = s
    }

Do you have an idea what to do?

The best solution is to make properties optional.


Note that

[String?]

is not optional.


BNut

[String]?


would be.