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?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With