如何创建一个字典数组?

Tom*_*thy 2 arrays struct dictionary swift

新编程!

我正在尝试在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)
Run Code Online (Sandbox Code Playgroud)

这在游乐场中运行良好,但是当我将它放入Xcode项目中时,在struct中,带有append函数的行会产生错误"Expected declaration".

我也尝试使用+ =运算符,结果相同.

如何在struct中成功构造这个数组?

rin*_*aro 10

根据你的错误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)
}
Run Code Online (Sandbox Code Playgroud)

这是因为只能在结构体中放置"声明",而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)
    }
}
Run Code Online (Sandbox Code Playgroud)

但作为@AirspeedVelocity提到的,你应该提供有关的更多信息myArray,或者myArrayArray<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]
}
Run Code Online (Sandbox Code Playgroud)

但是,我不知道,你为什么不这样做:

struct Foo {

    var myArray = [
        [
            "a": "1",
            "b": "2",
            "c": "3",
        ],
        [
            "a": "4",
            "b": "5",
            "c": "6",
        ]
    ]
}
Run Code Online (Sandbox Code Playgroud)


Air*_*ity 6

问题在于这条线:

var myArray = [[ : ]]
Run Code Online (Sandbox Code Playgroud)

你需要告诉Swift什么类型myArray- [[:]]信息不足.

您可以以明确的方式执行此操作:

var myArray: [[String:String]] = [[ : ]]
Run Code Online (Sandbox Code Playgroud)

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

var myArray = [dictionaryA]
var myArray = [dictionaryA,dictionaryB]
Run Code Online (Sandbox Code Playgroud)

(作为显式空版本的替代,你也可以写var myArray = [[String:String]](),这是简写var myArray = Array<Dictionary<String,String>>())