简体   繁体   中英

Variable nil in one function

I'm using latest Xcode Version 8.0 (8A218a) and Swift 3.0.

I'm working with a UIScrollview (m_scrollView) that is correctly allocated and used.

When callbackForceUpdateEvent is called, m_scrollView is OK but right after, when calling showEvents I got the error: fatal error: unexpectedly found nil while unwrapping an Optional value when trying to print its description (A). I also got this error if I try to access its subviews(B). But, I can add subviews to it (C), and it's displayed correctly. Only printing its description or accessing its subviews failed.

override func callbackForceUpdateEvent(_ event: Event) {

        print (self.m_scrollView) // works fine

        self.showEvents()
    }

func showEvents() {
     /*(A)*/ print (self.m_scrollview) // fatal error: unexpectedly found nil while unwrapping an Optional value

     /*(B)*/ for view in m_scrollview.subviews { // fatal error: unexpectedly found nil while unwrapping an Optional value
     }

     /*(C)*/ m_scrollView.addSubview(v) // works fine !!!
}

It's driving me crazy since 2 days now.

I tried to rename my variable and it's working fine now. And I understood my mistake: the variable m_scrollview was also declared in the superclass.

I don't know why the Swift compiler didn't tell me that. But after renaming back the variable, Swift told me it...

Problem solved!

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