0

I don't see why execution falls into the debugPrint statement here, when the variables window (and print statements) show that test is nil:

                let test = cxticsByUuid[cxtic.uuid]
                if test != nil
                {
                    debugPrint("Duplicate cxtic retrieved. Bailing out of peripheral's didDiscoverCharacteristicsFor...")
                    return
                }

UPDATE: Although the variables window shows that the variable in question is nil, it is in fact a double optional. So it must be unwrapped twice, as illustrated in the associated post.

enter image description here

Oscar
  • 2,039
  • 2
  • 29
  • 39
  • In short: use `if let test = cxticsByUuid[cxtic.uuid] ?? nil { ... }` – pawello2222 Sep 29 '20 at 18:28
  • 1
    @pawello2222 I think you've nailed the problem, but this isn't a duplicate IMO (it wouldn't be clear to many readers why this is the cause). If you're willing to write an answer that explains what's going on here, that would likely be very helpful. (Particularly explaining why `nil != .some(nil)`.) – Rob Napier Sep 29 '20 at 18:29
  • 1
    @RobNapier I've read the vacawama's answer to the duplicate question and it seemed pretty clear and detailed. I don't think it misses anything. – pawello2222 Sep 29 '20 at 18:33
  • 2
    If Oscar understands (and they seem to), then that indicates it's certainly close enough. Thanks. – Rob Napier Sep 29 '20 at 18:34
  • Yes, it wasn't until after posting this that I even noticed the double optional, but I left it because the behavior might be perplexing; everything shows that the variable in question is nil. – Oscar Sep 29 '20 at 20:39

1 Answers1

-1

You should use a if let in this scenario.

if let test = cxticsByUuid[cxtic.uuid] {
    debugPrint("Duplicate cxtic retrieved. Bailing out of peripheral's didDiscoverCharacteristicsFor...")
} else {
    //variable test is nil
}
Nathan Walsh
  • 358
  • 2
  • 4
  • Thanks, but that fails in exactly the same way. I did not mod you down. – Oscar Sep 29 '20 at 18:26
  • That is not the case, you can do that this way when you want to access non-optional variable inside if let, the case provided there is valid as well to check if it not nil. – D. B. Sep 29 '20 at 18:27
  • 2
    Doesn't this simply add a useless compiler warning about `test` being unused? – Gereon Sep 29 '20 at 18:29
  • @Gereon You can always omit the `else {...}` part if you don't need to do anything in the nil case. – Caleb Sep 29 '20 at 18:39
  • 2
    You could avoid the compiler warning by using `if let _ = cxticsByUuid[cxtic.uuid]`. But the solution in this answer won't solve the double optional problem. – Duncan C Sep 29 '20 at 19:25