Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protocol defining singleton with properties

I have the following protocol that defines a singleton with property:

protocol SingletonProtocol {
    static var shared: SingletonProtocol { get }
    var variable : Int { get set }
}

And the following class that implements this protocol:

class Singleton : SingletonProtocol{
    static let shared : SingletonProtocol = Singleton()
    var variable = 4
}

If I call:

Singleton.shared.variable = 5

I get the following error:

 change 'let' to 'var' to make it mutable

If I implement this class without the protocol I don't get the error and the variable can be changed. I can solve this by adding setVariable: method but I want to access and modify the variable directly.

How can I write a protocol that defines a singleton with variables that can be modified?

like image 395
amir Avatar asked Aug 09 '26 18:08

amir


1 Answers

Make the protocol available only for classes (struct won't be able to conform to this protocol):

protocol SingletonProtocol: AnyObject {
    static var shared: SingletonProtocol { get }
    var variable: Int { get set }
}

Now you can set the shared property as a let

class Singleton: SingletonProtocol {
    static let shared: SingletonProtocol = Singleton()
    var variable: Int = 0
}
like image 156
Rico Crescenzio Avatar answered Aug 12 '26 01:08

Rico Crescenzio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!