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]?
, ie 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]? = [:]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.