-1
var dist: Dictionary<String, NSObject>!
var bigDist : Dictionary<String, Dictionary<String, NSObject>>!

self.bigDist["1" as String] = self.dist

When I try to do this, I get an error:

fatal error: unexpectedly found nil while unwrapping an Optional value

Data set for self.dist:

Optional(["hits": 0, "name": India lags behind China in consumer spends: Stefano Ricci’s Jackie Manglani, "web": Livemint, "id": -1655, "like": 0, "iurl": http://www.livemint.com/rf/Image-222x148/LiveMint/Period2/2017/02/21/Photos/Processed/jackiemanglani2-kXhC--621x414@LiveMint.JPG, "notify": 0, "date": 201655200217, "active": 1, "type": Mark, "dateAdded": 20/02/2017, "url": http://www.livemint.com/Consumer/3NT8Vbw7BcGeoPJNMoyK5H/India-lags-behind-China-in-consumer-spends-Stefano-Riccis.html])
Akshay Chugh
  • 29
  • 1
  • 4
  • Well yes, because `bigDist` is `nil`. You need to initialise it (and it should almost certainly be non-optional). – Hamish Feb 20 '17 at 20:07

2 Answers2

0

Your variable bigDist is an implicitly unwrapped optional. (You declare it with) your_type!.

That means that:

  1. It can contain a nil.
  2. You don't need to unwrap it using ? or !.
  3. If you reference it and it contains nil, you'll crash.

Number 3 is what's happening.

You need to create an empty dictionary. Try getting rid of the ! in the declaration, and creating an empty dictionary when you declare it:

var bigDist : Dictionary<String, Dictionary<String, NSObject>> = [:]
Duncan C
  • 128,072
  • 22
  • 173
  • 272
0

You did not initialize bigDist:

var dist: Dictionary<String, NSObject>? = nil
var bigDist = Dictionary<String, Dictionary<String, NSObject>>()

self.bigDist["1"] = self.dist

The code could be swiftier anyway. Using [String: NSObject] instead of Dictionary<String, NSObject> (which is exactly the same) makes the code easier to read and can prevent such a mistake like you did.

var dist: [String: NSObject]? = nil
var bigDist = [String: [String: NSObject]]()

self.bigDist["1"] = self.dist
FelixSFD
  • 6,052
  • 10
  • 43
  • 117