Shohrab
Shohrab

Reputation: 546

Swift 2 create singleton class and Initialize value

I am trying to create a singleton class. Unable to initialize value. here is my code -

import UIKit

class SHProxy: NSObject {

    static let sharedInstance = SHProxy()
    var questionClickCount = 0
    var overlayView : UIView
    private override init() {
        overlayView = loadOverLayView()  //Error is in this line
    }

 private func loadOverLayView() -> UIView{
        let nibName = NSBundle.mainBundle().loadNibNamed("SHOverlayView", owner: self, options: nil)
        return nibName[0] as! UIView
    }

}

Error: Use of self In method call "loadOverLayView" before super.init initialize self

Upvotes: 1

Views: 624

Answers (2)

Sean G
Sean G

Reputation: 499

The reason you're receiving the error is because you have not called the super's initializer before accessing any of the derived class's variables or functions. Since you must initialize all optionals before calling the super's initializer your current logic will not work. Instead use a lazy property:

lazy var overlayView: UIView = {
   return self.loadOverLayView()
}()

Upvotes: 0

Midhun MP
Midhun MP

Reputation: 107141

You can't use self (or any call to self) before super.init(). But in your case you can't add super.init() as the first statement of the function since the overlayView is a non-optional value (It will throw another error like "property self.overlayView not initialised at super.init call)

Instead of doing like that way, you can use computed property to handle this situation.

class SHProxy: NSObject {

    static let sharedInstance = SHProxy()
    var questionClickCount = 0
    var overlayView : UIView
    {
        get
        {
            let nibName = NSBundle.mainBundle().loadNibNamed("SHOverlayView", owner: self, options: nil)
            return nibName[0] as! UIView
        }
    }

    private override init()
    {
        super.init()
    }
}

Upvotes: 1

Related Questions