mjr mjr - 4 months ago 11
Swift Question

Object is nil only in dictionary

If I declare and set a variable at the top of a class, like

class Test {
var timer = NSTimer()
...


and test its validity in a function later, like
if timer.valid {...}
, no problem. But if I put it in a dictionary

var timers = ["first": NSTimer(), ...]


and test that with
if timers["first"]!.valid {...}
, I get an "unexpectedly found nil" fatal error at runtime. Why are these behaviors different, and how can I get the dictionary not to throw out my timer initialization? If this is a duplicate please point it out, I just don't really know what to search for. The Dictionary docs didn't shed any light, and I haven't tried it with anything but
NSTimer
.

Answer

This is a bug in Foundation and you should open a defect. NSTimer() is not a valid initializer and it should be marked as unavailable. A similar thing occurs with NSError by the way. Swift lets you construct them with NSError() even though they are then invalid and will crash if you try to use them.

The fact that you happen to get away with it, and it likely is returning "false" due to nil-messaging (which is how ObjC works), shouldn't be seen as "it should work." NSTimer() is invalid code.

Comments