0
class whatever {
    var optional_dict : [Int : Int]? = nil

    init() {
        optional_dict![10] = 100
        print(optional_dict)
    }
}

when i try to print it showed like this "fatal error: unexpectedly found nil while unwrapping an Optional value" I don't know what mistake am doing. Could someone help me to sort it out. Thanks in advance.

rmaddy
  • 314,917
  • 42
  • 532
  • 579

1 Answers1

0

You declared an optional dictionary but never initialized it.

Change the code to this:

var optional_dict : [Int : Int]? = [Int : Int]()

EDIT:

Try this in playgrounds (OK Code)

class WhateverClass {
    var optional_dict : [Int : Int]? = [Int : Int]()

    init() {
        optional_dict![10] = 100
        print(optional_dict)

        optional_dict = nil

        print(optional_dict)

    }
}

var myClass = WhateverClass()

VS this (BAD Code):

class WhateverClass {
    var optional_dict : [Int : Int] = [Int : Int]()

    init() {
        optional_dict![10] = 100
        print(optional_dict)

        optional_dict = nil

        print(optional_dict)

    }
}

var myClass = WhateverClass()

Without explicitly declaring it as an optional you wouldn't be able to nil it after.

Pochi
  • 13,391
  • 3
  • 64
  • 104
  • 1
    Then what's the point of making it optional? – rmaddy Jun 29 '17 at 06:28
  • Well, I dunno, maybe he will nil it sometime in the future? – Pochi Jun 29 '17 at 06:30
  • @rmaddy Maybe it's a kind of class that has a valid value at the beginning but when some condition is met it should nill itself as unusable? I honestly don't know what he wants to accomplish but it has to explicitly be declared as an optional while giving it an initial value to fit in his code. Yeah you could just not make it an optional but then you wouldn't be able to nil it after. – Pochi Jun 29 '17 at 06:37