Search code examples
swiftxcodexcode11swift5swift-optionals

Problem: My non optional variable is nil. (Fatal Error while unwrapping)


I am trying to update an UILabel.

@IBOutlet weak var balanceLabel: UILabel!

it is initially declared as a non optional variable:

var balanceValue: Int = 1

The UILabel depends on the not optional variable balanceValue.

func updateBalanceLabel() {
        balanceLabel.text = String(balanceValue) }

That all worked fine, but at some point I got this fatal error, which wont go away:

Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

The error is referring to this line:

balanceLabel.text = String(balanceValue)

That does not make any sense... I am having a non optional variable which is declared as 1 per default. How can it be nil.

Here is the crashlog:

> libswiftCore.dylib`_swift_runtime_on_report:
->  0x7fff51b801c0 <+0>: pushq  %rbp 
    0x7fff51b801c1 <+1>: movq   %rsp, %rbp
    0x7fff51b801c4 <+4>: popq   %rbp
    0x7fff51b801c5 <+5>: retq   
    0x7fff51b801c6 <+6>: nopw   %cs:(%rax,%rax)

and

ibswiftCore.dylib`Swift._assertionFailure(_: Swift.StaticString, _: Swift.String, file: Swift.StaticString, line: Swift.UInt, flags: Swift.UInt32) -> Swift.Never:
    0x7fff518d9370 <+0>:  pushq  %rbp
    0x7fff518d9371 <+1>:  movq   %rsp, %rbp
    0x7fff518d9374 <+4>:  movl   0x28(%rbp), %eax
    0x7fff518d9377 <+7>:  movl   0x18(%rbp), %r10d
    0x7fff518d937b <+11>: pushq  %rax
    0x7fff518d937c <+12>: pushq  0x20(%rbp)
    0x7fff518d937f <+15>: pushq  %r10
    0x7fff518d9381 <+17>: pushq  0x10(%rbp)
    0x7fff518d9384 <+20>: callq  0x7fff51adf410            ; function signature specialization <Arg[0] = Exploded, Arg[1] = Exploded> of Swift._assertionFailure(_: Swift.StaticString, _: Swift.String, file: Swift.StaticString, line: Swift.UInt, flags: Swift.UInt32) -> Swift.Never
->  0x7fff518d9389 <+25>: addq   $0x20, %rsp
    0x7fff518d938d <+29>: ud2    
    0x7fff518d938f <+31>: nop

What weirds me out, that I did not change the working code, but now all of a sudden I get this problem. Restarting XCode wont solve it. Tried different things to pin down the problem, but I cant find the reason why balanceValue should be nil. Any help greatly appreciated.


Solution

  • Its nil because your outlet is broken. Since you declared it as an implicitly unwrapped optional, balanceLabel.text = String(balanceValue) is the same as balanceLabel!.text = String(balanceValue). You can verify this is tru by simply using optional unwrapping (an implicitly unwrapped optional is still an optional): balanceLabel?.text = String(balanceValue). Go into your storyboard, right click the label and look at the connections. break any existing connections and then recreate the binding to your variable.