如何创建一个字典数组? [英] How to create an array of dictionaries?

查看:214
本文介绍了如何创建一个字典数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新的编程!

我试图在Swift的一个结构体内创建一个字典数组,如下所示:

I'm trying to create an array of dictionaries inside a struct in Swift like so:

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项目中,在一个结构体中,带有append函数的行会产生错误

This works fine in a playground, but when I put it into an Xcode project, inside a struct, the lines with the append function produce the error "Expected declaration".

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

I've also tried using the += operator with the same result.

我可以在结构体内成功构建这个数组吗?

How can I successfully construct this array inside the struct?

推荐答案

从你的错误预期声明,我假设你这样做:

From your error Expected declaration, I assume you are doing like:

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

是因为你可以在结构体中放置只有声明,而 myArray.append(dictionaryA)不是声明

This is because you can place only "declarations" in the struct body, and myArray.append(dictionaryA) is not a declaration.

您应该在别的地方执行,例如在初始化程序中。以下代码编译。

You should do that somewhere else, for example in the initializer. The following code compiles.

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> ,我认为你不期望。

But as @AirspeedVelocity mentioned, you should provides more information about myArray, or myArray would be Array<NSDictionary> which I think you don't expect.

正确的解决方案将根据您真正尝试的方式而有所不同:

Anyway, the correct solution would vary depending on what you really trying to do:

也许或许不是,你想要的是:

Maybe or maybe not, what you want is something like:

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

    var myArray = [dictionaryA, dictionaryB]
}

但是,我不知道,为什么不只是:

But, I don't know, why don't you just:

struct Foo {

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

这篇关于如何创建一个字典数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆