如何创建字典数组?

How to create an array of dictionaries?

编程新手!

我正在尝试在 Swift 中的结构中创建字典数组,如下所示:

var dictionaryA = [
    "a": "1",
    "b": "2",
    "c": "3",
    ]
var dictionaryB = [
    "a": "4",
    "b": "5",
    "c": "6",
    ]
var myArray = [[ : ]]
myArray.append(dictionaryA)
myArray.append(dictionaryB)

这在操场上工作正常,但是当我将它放入一个 Xcode 项目中时,在一个结构中,带有附加函数的行产生错误 "Expected declaration".

我也试过使用 += 运算符得到相同的结果。

如何在结构中成功构建这个数组?

问题出在这一行:

var myArray = [[ : ]]

您需要告诉 Swift myArray 是什么类型 – [[:]] 信息不够。

您可以通过显式方式进行:

var myArray: [[String:String]] = [[ : ]]

或者,如果可行,隐式使用您计划输入的第一个或两个值:

var myArray = [dictionaryA]
var myArray = [dictionaryA,dictionaryB]

(作为显式空版本的替代方案,您还可以编写 var myArray = [[String:String]](),即 shorthand for var myArray = Array<Dictionary<String,String>>()

根据你的错误 Expected declaration,我假设你是这样做的:

struct Foo {
    var dictionaryA = [
        "a": "1",
        "b": "2",
        "c": "3",
    ]
    var dictionaryB = [
        "a": "4",
        "b": "5",
        "c": "6",
    ]
    var myArray = [[ : ]]
    myArray.append(dictionaryA) // < [!] Expected declaration
    myArray.append(dictionaryB)
}

这是因为you can place only "declarations" in the struct body,而myArray.append(dictionaryA)不是声明。

您应该在其他地方执行此操作,例如在初始化程序中。以下代码编译。

struct Foo {
    var dictionaryA = [
        "a": "1",
        "b": "2",
        "c": "3",
    ]
    var dictionaryB = [
        "a": "4",
        "b": "5",
        "c": "6",
    ]
    var myArray = [[ : ]]

    init() {
        myArray.append(dictionaryA)
        myArray.append(dictionaryB)
    }
}

但是正如@AirspeedVelocity 提到的,您应该提供有关 myArray 的更多信息,否则 myArray 将是 Array<NSDictionary>,我认为您不会想到。

无论如何,正确的解决方案会因您真正尝试做的事情而异:

可能是也可能不是,你想要的是这样的:

struct Foo {
    static var dictionaryA = [
        "a": "1",
        "b": "2",
        "c": "3",
    ]
    static var dictionaryB = [
        "a": "4",
        "b": "5",
        "c": "6",
    ]

    var myArray = [dictionaryA, dictionaryB]
}

但是,我不知道,你为什么不直接:

struct Foo {

    var myArray = [
        [
            "a": "1",
            "b": "2",
            "c": "3",
        ],
        [
            "a": "4",
            "b": "5",
            "c": "6",
        ]
    ]
}

或者您可以使用更简单的元组数组,如下所示:

var myArray:[(a:String,b:String,c:String)] = []

并附加您稍后需要的任何元素:

self.myArray.append((a:"A",b:"B",c:"c"))

并且只需使用它们:

self.myArray[index].a
self.myArray[index].b
self.myArray[index].c
var arrayOfDict = [[String: Int]]()
// Create a dictionary and add it to the array.
var dict1: [String: Int] = ["age": 20]
arrayOfDict.append(dict1)
// Create another dictionary.
var dict2: [String: Int] = ["rank": 5].
arrayOfDict.append(dict2)
// Get value from dictionary in array element 0.
if let value = arrayOfDict[0]["age"] {
print(value)
}

输出

20