我需要更新存储在 Array
中的 Enum
的关联值。如何在不知道其索引的情况下访问正确案例的单元格?
enum MessageCell {
case from(String)
case to(String)
case subject(String)
case body(String)
}
var cells = [MessageCell.from(""), MessageCell.to(""), MessageCell.subject(""), MessageCell.body("")]
let recipient = "John"
// Hardcoded element position, avoid this
cells[1] = .to(recipient)
// How to find the index of .to case
if let index = cells.index(where: ({ ... }) {
cells[index] = .to(recipient)
}
最佳答案
使用if case
来测试闭包中的enum
case .to
,如果找到则返回true
, 否则返回 false
:
if let index = cells.index(where: { if case .to = $0 { return true }; return false }) {
cells[index] = .to(recipient)
}
这是一个完整的例子:
enum MessageCell {
case from(String)
case to(String)
case subject(String)
case body(String)
}
var cells: [MessageCell] = [.from(""), .to(""), .subject(""), .body("")]
if let index = cells.index(where: { if case .to = $0 { return true }; return false }) {
print(".to found at index \(index)")
}
输出:
.to found at index 1
关于swift - 如何获取数组中枚举案例的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44239997/