My dictionary is always nil, would like to understand why this is happening. My code:
var dic = [NSDate : MCACalendar]?() dic?[currentDate!] = calendar @Kirsteins provides the solution - but it's good to know why.
Using [NSDate : MCACalendar]?() doesn't work as you expect because it creates an instance of [NSDate : MCACalendar]?, i.e. an instance of an optional - to be more precise, an instance of Optional<[NSDate : MCACalendar]>. So that initialization doesn't create an instance of [NSDate : MCACalendar].
Creating an instance of an optional (Optional<T>) using the parameterless constructor initializes it to .None (equivalent to nil), so for example in:
var x = Int?() // `x` is initialized as `.None` If a parameter is passed to the constructor, then the optional variable is initialized with .Some:
var x = Int?(5) // x is initialized as `.Some(5)` That explains Kirsteins's solution no. 1. Solution no. 2 is so obvious that it doesn't need further explanation :)
It seems [NSDate : MCACalendar]?() fails and returns nil. You probably want to use:
var dic = [NSDate : MCACalendar]?([:]) or
var dic: [NSDate : MCACalendar]? = [:] nil. What was the line that was crashing?currentDate is nil.