【问题标题】:Swift 4 append items to a specific section in a structured arraySwift 4 将项目附加到结构化数组中的特定部分
【发布时间】:2018-08-24 16:42:15
【问题描述】:

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

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)

【问题讨论】:

  • 使用 var 而不是 let stackoverflow.com/questions/24002092/…
  • 将 let 更改为 vars,但在我尝试附加的最后一行得到以下表格:无法将类型“[String]”的值转换为预期的参数类型“String”

标签: arrays swift append swift4


【解决方案1】:

删除以下代码

  objects[0].items.append(reptiles)

使用此代码:

objects[0].items +=  reptiles

Swift 5 更新:

在 Swift 5 中,此解决方案将不起作用,您将收到类似的错误

"变异操作符的左边是不可变的:'items' 是 'let' 常数”

解决办法是改变结构:

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

【讨论】:

    猜你喜欢
    • 2018-10-10
    • 1970-01-01
    • 2018-03-18
    • 2020-04-12
    • 2015-10-11
    • 1970-01-01
    • 2016-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多