swift - 如何获取数组中枚举案例的索引

标签 swift enums

我需要更新存储在 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/

相关文章:

ios - 如何提高 ARKit 测量两个 SCNNode 之间距离的准确性?

ios - Swift:关于协议(protocol)和委托(delegate)模式

C Language : trouble using enumerated variable and type definited in main. c文件在另一个文件里面

c# - 枚举创建断点

c# - enum.toString() 是如何工作的?

ios - 从不同的项目下载和使用存储在 Firebase Storage 中的文件

json - 使用 JSON-API 获取的字符串在 Swift 中从 base64 转换为 UTF8

swift - NSURLSession 将文件上传到服务器 Swift

java - 模拟 Java 枚举以添加一个值来测试失败案例

java - 如何使用采用某些枚举类型实例的方法创建接口(interface)?