Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot use instance member within property initializer; property initializers run before 'self' is available

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.
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading