简体   繁体   中英

How to factorize Swift class initialization in order to avoid redundant code?

I am trying to do a custom UIPickerView. In my custom class, I have to override "init(coder aDecoder: NSCoder)" initializer.

In the same time I want to have an initialiser without any parameter. According to error message, my class variables initialization is mandatory, but their initialization is not detected if done in a separate function.

class MyPickerView: UIPickerView{
   var maxInt:CInt;    

   func baseInit(){
      maxInt = 10;
   }

   override init() {
      maxInt = 10;
      super.init();
   }

   required init(coder aDecoder: NSCoder) {
      maxInt = 10;
      super.init(coder: aDecoder)
   }    
}

There, I do have redundant code for my "maxInt" initialization.

If I replace the intialization of maxInt in the initializer, I have this error message:

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

What should I do. What should the best practice?

Thank you for your help.

You can make the var optional or initialize in at the declaration

class MyPickerView: UIPickerView {
   var maxInt:CInt = 10 // or var maxInt:CInt?   
}

or

class MyPickerView: UIPickerView {
   var maxInt:CInt?

   func setup() {
     maxInt = 10
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM