2

My dictionary is always nil, would like to understand why this is happening. My code:

var dic = [NSDate : MCACalendar]?() dic?[currentDate!] = calendar 

2 Answers 2

3

@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 :)

Sign up to request clarification or add additional context in comments.

Comments

1

It seems [NSDate : MCACalendar]?() fails and returns nil. You probably want to use:

var dic = [NSDate : MCACalendar]?([:]) 

or

var dic: [NSDate : MCACalendar]? = [:] 

4 Comments

I got the error: "fatal error: unexpectedly found nil while unwrapping an Optional value"
As error states you unwrapped something that is nil. What was the line that was crashing?
the line: "tempDic?[currentDate!] = calendar"
I guess that currentDate is nil.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.