使用字符串数组作为值在swift中创建字典

时间:2015-11-27 11:33:28

标签: arrays swift dictionary

在swift中创建字典时,字符串数组的值如下:

lazy var info : Dictionary = {

    var dictionary = [String: [String]]()
    dictionary["Key1"] = ["A", "B", "C"]
    dictionary["Key2"] = ["D", "E", "F"]

    return dictionary  
}()

无法分配给'Value?'

类型的不可变表达式

这里有什么想法吗?

2 个答案:

答案 0 :(得分:5)

我已经看到了你自己的答案,但这有一个更好的方法:在你的案例[String: [String]]中声明其正确的类型使用Swift字典:

lazy var info : [String: [String]] = {

    var dictionary = [String: [String]]()
    dictionary["Key1"] = ["A", "B", "C"]
    dictionary["Key2"] = ["D", "E", "F"]

    return dictionary
}()

答案 1 :(得分:0)

更改

lazy var info : Dictionary = {

    var dictionary = [String: [String]]()
    dictionary["Key1"] = ["A", "B", "C"]
    dictionary["Key2"] = ["D", "E", "F"]

    return dictionary  
}()

lazy var info : NSDictionary = {

    var dictionary = [String: [String]]()
    dictionary["Key1"] = ["A", "B", "C"]
    dictionary["Key2"] = ["D", "E", "F"]

    return dictionary  
}()

一切都很好:)