Search code examples
swiftnulloption-typeunwrap

Xcode unexpectedly found nil while unwrapping an Optional, but no idea why


Xcode gives me the following error but I have no idea where this is coming from. I printed elpasedTime value and it contains the value! But it still says it found nil when unwrapping and I have no clue why this happens since it doesn't tell me where.

Where could this possibly go wrong??

The function stringFromTimeInterval is as below

extension TimeInterval {

func stringFromTimeInterval() -> String {

    let time = NSInteger(self)

    //        let ms = Int((self.truncatingRemainder(dividingBy: 1)) * 1000)
    let seconds = time % 60
    let minutes = (time / 60) % 60
    let hours = (time / 3600)
    print("5 here?")
    return String(format: "%0.2d:%0.2d:%0.2d",hours,minutes,seconds)

}

}

enter image description here


Solution

  • Solved it.

    As the comments pointed out, the problem was that I was not accessing ViewController correctly.

    In order to access my ViewController outside of the ViewController class, I was creating a new instance of it by ViewController().

    I solved it by putting the function inside the class and changing ViewController() part to self.ViewController.

    This answer also helped me as well. https://stackoverflow.com/a/45932084/7414387