如何获取数组中枚举大小写的索引

Mar*_*les 2 enums swift

我需要更新Enum存储在中的关联值Array。如何在不知道其索引的情况下访问适当大小的单元格?

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)
}
Run Code Online (Sandbox Code Playgroud)

vac*_*ama 7

使用if case测试的enum情况下,.to在封闭和返回true如果找到了,否则返回false

if let index = cells.index(where: { if case .to = $0 { return true }; return false }) {
    cells[index] = .to(recipient)
}
Run Code Online (Sandbox Code Playgroud)

这是一个完整的示例:

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)")
}
Run Code Online (Sandbox Code Playgroud)

输出:

.to found at index 1
Run Code Online (Sandbox Code Playgroud)