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?