Swift 3:查找索引并从Structs数组中的数组中删除一个项目

Enz*_*nzo 0 arrays indexing struct swift

我正在使用struct来填充带有节和行的表视图控制器.现在我需要从表中删除一个单元格.如何在列表中找到要删除的元素?

结构:

struct Cells {
    var section: String!
    var list: [String]!
}
Run Code Online (Sandbox Code Playgroud)

部分和行

var tableStructure = [Cells(section: "Requests", list: ["uidU", "uidV"])]
Run Code Online (Sandbox Code Playgroud)

用于在结构中搜索要从列表中删除的元素,从结构列表中删除项目然后从表视图中删除单元格的代码:

let index = tableStructure.index(where: {$0.section == "Requests" && list.index{$0 == cell.selectedUserUid} as Any as! Bool})
self.tableStructure.remove(at: index!) //***ERROR HERE***
tableView.deleteRows(at: [indexPath], with: .fade)
Run Code Online (Sandbox Code Playgroud)

错误信息:

fatal error: unexpectedly found nil while unwrapping an Optional value
Run Code Online (Sandbox Code Playgroud)

我设置了一个断点来查看"cell.selectedUserUid"的内容,它等于我想从struct中删除的元素.

建议?谢谢!

vad*_*ian 5

结果index总是Int?意味着它可以是Intnil但从不Bool(顺便说一句as Any as! Bool是一种可怕的语法).

你可能想要这个(list数组包含Uid)

tableStructure.index(where: {$0.section == "Requests" && $0.list.contains(cell.selectedUserUid)})
Run Code Online (Sandbox Code Playgroud)

应该 必须安全地写

if let index = tableStructure.index(where: {$0.section == "Requests" && $0.list.contains(cell.selectedUserUid)}) {
    self.tableStructure.remove(at: index)
    tableView.deleteRows(at: [indexPath], with: .fade)
}
Run Code Online (Sandbox Code Playgroud)

编辑

你的设计无法运作.您将删除整个非意图的部分.添加变异功能的结构(或使用类),除去特定项目list.然后重新创建相应的indexPath.如果数组为空,则可以删除该部分.


重要的提示:

永远不要将类/结构中的属性/成员声明为将使用init方法初始化的隐式解包选项.如果你想要一个可选的使用常规的optional(?),否则一个非可选的(no ?!)