ios - 如何从使用结构创建的数组中追加一个项目?

标签 ios arrays swift4

我在 ios 中有一个表,我希望将一个数组中的选定项附加到另一个数组,但是当我尝试时出现错误 Cannot subscript a value of type '[VintageThings]' with an index类型为“IndexPath”

这是给我错误的代码,我尝试查找如何执行此操作,但所有答案似乎都与单层数组有关,例如 array = ["dog","cat"] 等。请帮我解决这个问题。

var selected: [VintageThings] = []

func tableView(tableView: UITableView, didSelectRowAt IndexPath: IndexPath) {
   selected.append(newArray[indexPath])
}

编辑

如何获取 selected 数组以锁定来自多个场景的项目并在以后的场景中可用?我是否必须在外部 swift 文件中设置数组?我不知道项目是否正在保存到它。

最佳答案

IndexPath 由两个索引组成。你想要的是 indexPath.row。 那是因为 TableView 也可以分成几个部分。如果用户点击给定部分中的某个项目,您会想知道是哪一个。这就是 IndexPath 有第二个索引 indexPath.section 的原因。

要再次从数组中删除它,您必须使用相同的方法(一种切换行为)

let element = newArray[indexPath.row];
if selected.contains(element) {
   selected = selected.filter {$0 = element}
} else {
   selected.append(element)
}

关于ios - 如何从使用结构创建的数组中追加一个项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51319679/

相关文章:

ios - 将背景图像缩放到 iPhone 10

ios - CALayer : Where does the implicit animation comes from?

c# - 如何将数组中的所有内容向上移动一个位置? C#

java - 读取文本文件中的空行

ios - 如何在 swift 4 的 Collection View 中刷新数据?

swift - 不符合 Decodable/Codable 协议(protocol)

ios - FaSTLane快照可以在真实的ios设备上运行吗?

iphone - 自定义 View Controller 委托(delegate)不起作用

Javascript - Chrome 控制台 - "Array(0)"是什么意思?

ios - 快速和核心图形,捕捉点并撤消图像