Swift 4 将项目附加到结构化数组中的特定部分



我希望(根据此示例(在创建初始条目后向结构化数组的特定部分添加更多项目。

struct Zoo {
    let section: String
    let items: [String]
}
var objects = [Zoo]()
let animals = Zoo(section: "Animals", items: ["Cat","Dog","Mouse"])
let birds = Zoo(section: "Birds", items: ["Crow","Pidgeon","Hawk"])
let reptiles = ["Snake","Lizard"]
objects.append(animals)
objects.append(birds)
// ... varous logic and proccessing where I determine I need 
// to add two more items to the animals section...
// trying to extend animals with two more entries.
// this is where I am getting hung up:
objects[0].items.append(reptiles)

删除以下代码

  objects[0].items.append(reptiles)

使用此代码:

objects[0].items +=  reptiles

Swift 5 的更新:

在 Swift 5 中,此解决方案将不起作用,并且您会收到类似

">

突变运算符的左侧是不可变的:"项目"是'让'常数">

解决方案是改变结构:

struct Zoo {
    let section: String
    var items: [String]
}

最新更新