gpt4 book ai didi

arrays - Swift 4 将项目 append 到结构化数组中的特定部分

转载 作者:行者123 更新时间:2023-11-30 11:40:49 33 4
gpt4 key购买 nike

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

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 中,此解决方案将不起作用,您将收到类似错误

"Left side of mutating operator isn't mutable: 'items' is a 'let'constant"

解决方案是改变结构:

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

关于arrays - Swift 4 将项目 append 到结构化数组中的特定部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49306770/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com