Swift Compiler Issue?

I've encountered a strange issue with Swift and I wonder if this is a compiler error or if I didn't understand something correctly.

The following sample code shows a weird issue (please ignore that the demo code itself would not make that much sense in this form, it's just the version from a big and more complicated project, where this would make more sense):

class Test {

    var data: [String:[String:String]] = [:]

    func test() {
        let setValue: ((String, String, String) -> Void) = { [weak self] key, id, value in
            if self!.data[key] == nil {
                self!.data[key] = [:]
            }
            let oldValue = self!.data[key]![id]
            if oldValue == nil {
                self!.data[key]![id] = value
            }
        }
        
        setValue("0", "1", "2")
    }
}

When changing the "data" dictionary through the closure within the "test()" function, everything works as expected until the "if" condition where the oldValue is checked against nil. If I set a break point to this condition, the Xcode debugger tells me that oldValue is nil (which is expected), but the code within the if condition is NOT executed. The comparison oldValue == nil should be be true (because oldValue is actually nil), but the compiler seems to assume something else.

But If I do not user "self!" but instead "self?" then it does work as expected and the code within the if condition is executed.

What I am missing here? Is this the correct behavior or a compiler bug?

Thank you for your post. I have copied your code and am using Xcode 16.2. When I run the test() method and add a breakpoint, I am able to hit the breakpoint when oldValue is nil without any issues. Am I missing something? What Xcode version are you using? Have you moved the Test class into a unique, simple project to see how it behaves?

Albert Pascual
  Worldwide Developer Relations.

At least now it works. For unknown reasons it did not work in my main project yesterday, repeatedly. But since yesterday the code was changed a lot and the Mac was also restarted, so whatever has caused the glitch, it can no longer be reproduced.

Swift Compiler Issue?
 
 
Q