skip to Main Content

Here is the line where debugger stops:

let ystart = 24+Int((keyWindow?.safeAreaInsets.top)!)

And the bug comment: Thread 1: Swift runtime failure: force unwrapped a nil value.

I would add that the function above is executed every second. Maybe this will clarify the situation a bit.

2

Answers


  1. Chosen as BEST ANSWER

    I think I fixed, but I still don't understand the reason behind this problem. I added simple if statement like if (keyWindow?.safeAreaInsets.top != nil) {}


  2. Without more context, it‘s hard to find the real issue but at least we know, keyWindow hasn’t been set yet.

    yourMainWindow.makeKeyAndVisible() will set the keyWindow. It seems like the failing line is executed before makeKeyAndVisible() and therefore it is still nil.
    https://developer.apple.com/documentation/uikit/uiapplication/1622924-keywindow

    As mentioned in the comments, always think twice when force-unwrapping an optional, unless you are 100% sure it cannot become nil.

    Syntactic sugar:
    If you need to set a value that depends on an optional, you should also think about a fallback/default if the optional is nil. Using the coalescing operator (??) helps to avoid nil-check-if-statements like

    let ystart = 24+Int(keyWindow?.safeAreaInsets.top ?? yourDefaultValue)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search