无法在Swift中将对象添加到对象数组

时间:2019-04-23 06:48:10

标签: arrays swift

我想向var objectsArray添加一些新内容。我怎样才能做到这一点? append方法对我不起作用。

struct Objects {
    var sectionName : String!
    var sectionObjects : [String ]!
}

var objectsArray = [Objects]()   

objectsArray = [Objects(sectionName: "FirstSection", sectionObjects: ["hi"]),
                Objects(sectionName: "SecondSection", sectionObjects: ["Thomas Schmidt"])]

2 个答案:

答案 0 :(得分:0)

尝试一下,您的问题没有任何问题。

struct Objects {
    var sectionName : String!
    var sectionObjects : [String ]!
}

var objectsArrayUsingAppendFunc = [Objects]()
var objectsArrayWithoutAppendFunc = [Objects]()

objectsArrayUsingAppendFunc.append(Objects(sectionName: "FirstSection", sectionObjects: ["hi"]))
objectsArrayUsingAppendFunc.append(Objects(sectionName: "SecondSection", sectionObjects: ["Thomas Schmidt"]))
objectsArrayUsingAppendFunc.append(Objects(sectionName: "THIRD SECTI0N", sectionObjects: ["THIRD NAME"]))

objectsArrayWithoutAppendFunc = [ Objects(sectionName: "FirstSection", sectionObjects: ["hi"]),
                                  Objects(sectionName: "SecondSection", sectionObjects: ["Thomas Schmidt"]),
                                  Objects(sectionName: "THIRD SECTI0N", sectionObjects: ["THIRD NAME"])
                                ]

print(objectsArrayWithoutAppendFunc)
print("-----")
print(objectsArrayUsingAppendFunc)

答案 1 :(得分:0)

您可以使用以下代码来附加对象。一切正常。 从上面的代码中,我仅添加了一条追加行。

Buffer.alloc()