-2

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.
    }
  • I added an answer for how to resolve your compile error, but wanted to add a side note: It's hard to tell from the code you posted what the goal of `DateManager` is, but I would recommend giving it data (i.e. the values on each picker) rather than making `DateManager` aware of the actual UI controls. In that case it might make more sense to initialize it without `years` and `time` and rather set those properties in the delegate callback from the UIDatePickers. The error won't be relevant anymore then because you're not accessing class properties at the time of initialization. – mimo Aug 29 '22 at 19:16

1 Answers1

1

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)
mimo
  • 247
  • 1
  • 7