Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift initializer is inaccessible due to private protection level

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:

enter image description here Any of you know why or how I can fix this error?

like image 226
user2924482 Avatar asked Oct 17 '16 00:10

user2924482


1 Answers

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.

like image 189
rmaddy Avatar answered Nov 04 '22 02:11

rmaddy