1

I have the following in my View Controller:

required init(coder aDecoder: NSCoder) {

    selectedFocusAreas = Array()
    for _ in 0...focusAreas.count {
        selectedFocusAreas.append(false)
    }

    super.init(coder: aDecoder)!

}

This code compiles and doesn't give me any issues. However, when I try extract the code into a method like so:

required init(coder aDecoder: NSCoder) {
        setUpSelectedFocusAreaData()
        super.init(coder: aDecoder)!
    }

    func setUpSelectedFocusAreaData(){
        selectedFocusAreas = Array()
        for _ in 0...focusAreas.count {
            selectedFocusAreas.append(false)
        }
    }

I get the following compilation errors:

  • Use of self in method call setUpSelectedFocusAreaData before super.init initializes self
  • Property self.selectedFocusAreas not initialized at super.init call

Is there a way to have a method be called in the init method?

AshvinGudaliya
  • 3,234
  • 19
  • 37
user481610
  • 3,230
  • 4
  • 54
  • 101
  • 3
    Initialise `selectedFocusAreas` when you declare the property or in your initialiser and then call the function after you call `super.init` – Paulw11 Mar 31 '18 at 12:45
  • Please check this https://stackoverflow.com/a/24114372/2707648 – Hitendra Solanki Mar 31 '18 at 12:45
  • Be aware that your array contains one extraneous item. It's supposed to be either `0...focusAreas.count - 1` or `0.. – vadian Mar 31 '18 at 14:21

1 Answers1

0

@Paulw11 was on the money, you have to do the following:

required init(coder aDecoder: NSCoder) {
        selectedFocusAreas = Array()
        setUpSelectedFocusAreaData()
        super.init(coder: aDecoder)!
    }

    func setUpSelectedFocusAreaData(){
        for _ in 0...focusAreas.count {
            selectedFocusAreas.append(false)
        }
    }

i.e initialize the value first and then call the method.

user481610
  • 3,230
  • 4
  • 54
  • 101