Issue with optional binding using lazy var

20 Views Asked by At

I am working with a UIPageViewController and I have an array of viewcontrollers

lazy var subviewControllers: [UIViewController] = {
    return[
        UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ViewController1") as! ViewController1,
        UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ViewController2") as! ViewController2,
        UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ViewController3") as! ViewController3
    ]
}()

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if let subview3 = subviewControllers[2] as? ViewController3 {
        subview3.customBar.alpha = 0.8 // <- error on this line
    }
}

But sometimes I have this error when I make a scroll:

Unexpectedly found nil while unwrapping an Optional value

0

There are 0 best solutions below