Property 'self.*' not initialized at super.init call

前端 未结 3 1596
北荒
北荒 2020-12-09 16:50

I just updated my xcode to 6.3.1. The problem is I got this weird error message since Swift 1.2. I got this kind of error message

/Users/MNurdin/Documents/iO         


        
相关标签:
3条回答
  • 2020-12-09 17:19

    You have to initialize all property before you call super.init in any init method

    So,change this before you call super.init()

    originView = sourceView //error here
    

    Exception:

    1. optional property
    2. property with default value
    3. lazy property
    0 讨论(0)
  • 2020-12-09 17:20

    From Apple's “The Swift Programming Language” book:

    “Swift’s compiler performs four helpful safety-checks to make sure that two-phase initialization is completed without error”

    “A designated initializer must ensure that all of the “properties introduced by its class are initialized before it delegates up to a superclass initializer.”

    Basically you have to ensure that your instance variables are in a consistent state before you do anything, including calling methods.

    class YourClass {
        var view: UIView
        init(view: UIView) {
            self.view = view
        }
    }
    

    well in your case you can make it a new UIView:

    let originView = UIView()
    

    or make it nullable

    let originView: UIView?
    

    or make a lazy property instead:

    lazy var originView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: 375, height: 200))
        // customize it
        return view
    }()
    

    when using lazy instantiation you can pass a method:

    lazy var originView: UIView = self.createView()
    
    func createView() -> UIView {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: 375, height: 200))
            // customize it
            return view
    }
    
    0 讨论(0)
  • 2020-12-09 17:33

    Make your originView nullable by

    var originView: UIView?. 
    

    If your originView is not nullable you have to provide a default value before calling

    super.init().
    
    0 讨论(0)
提交回复
热议问题