如何在swift中向可选字典添加值

时间:2017-06-29 06:22:13

标签: swift

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

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

当我尝试打印时,显示出这样的“致命错误:在解开可选值时意外发现nil”我不知道我在做什么错误。有人可以帮我解决一下。提前谢谢。

1 个答案:

答案 0 :(得分:0)

您声明了一个可选字典但从未初始化它。

将代码更改为:

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

编辑:

在游乐场尝试此操作(确定代码

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此( BAD代码):

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()

如果没有明确地将其声明为可选项,您将无法在之后将其取消。