1

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

2 Answers 2

1

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()
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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()
}()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.