I'm trying to create a singleton in Swift but I'm getting this error:
initializer is inaccessible due to private protection level
Here is my code (singleton class)
class mySingleton{
private init() { }
static let sharedInstance = mySingleton()
var numbers = 0
func incrementNumberValue() {
numbers += 1
}
}
Here is where I'm calling the singleton:
override func viewDidLoad() {
super.viewDidLoad()
let single = mySingleton().sharedInstance
}
Here is the error:
Any of you know why or how I can fix this error?
Your line:
mySingleton().sharedInstance
has a typo. As written you are trying to create an instance of mySingleton
and then call the sharedInstance
method on the new instance. That's two mistakes.
What you actually want is:
mySingleton.sharedInstance
Now this calls the sharedInstance
type constant on your mySingleton
class.
BTW - it is expected that classnames begin with uppercase letters. Method and variable names should start with lowercase letters.
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