Home > OS >  Cannot use instance member within property initializer; property initializers run before 'self&
Cannot use instance member within property initializer; property initializers run before 'self&

Time:08-30

I have a structure and a viewcontroller below, I can't create that object I want to use. How can I fix it?

    import Foundation
        import UIKit
        struct DateManager{
        
            var years: UIDatePicker
            var time: UIDatePicker
        }
        
    import UIKit
        
        class HoroscopeViewController: UIViewController {
            
        
            
            
            @IBOutlet weak var cityText: UITextField!
            @IBOutlet weak var datePicker: UIDatePicker!
            @IBOutlet weak var timePicker: UIDatePicker!
            
            
            var dateManager = DateManager(years: datePicker, time: timePicker)
    
     //I want to create a structure object is here but cant use datePicker and timePicker here.
    }

CodePudding user response:

If you want to use one class property (or in this case two) to initialize another class property, you need a way to make sure the required properties have already been set.

If you mark dateManager as lazy it won't be initialized until it's accessed for the first time. By the time it can be accessed, self will be fully available so the compiler should be happy.

lazy var dateManager = DateManager(years: datePicker, time: timePicker)
  • Related