user2924482
user2924482

Reputation: 9140

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?

Upvotes: 5

Views: 11146

Answers (2)

jamal zare
jamal zare

Reputation: 1209

for using by instance object

class mySingleton{

private init() {    }

static let sharedInstance = mySingleton()

var sharedInstanceByInstance: mySingleton{
    return mySingleton.sharedInstance
}
//Usage: mySingleton().sharedInstanceByInstance

// or

func getShared()-> mySingleton{
    return mySingleton.sharedInstance
}   
 //Usage: mySingleton().getShared()
}

Upvotes: 0

rmaddy
rmaddy

Reputation: 318904

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.

Upvotes: 11

Related Questions