【问题标题】:How to get index of enum case in array如何在数组中获取枚举案例的索引
【发布时间】:2017-05-29 10:15:32
【问题描述】:

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

【问题讨论】:

标签: swift enums


【解决方案1】:

使用if case测试闭包中的enum案例.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

【讨论】:

  • 闭包必须如此复杂,这很糟糕; cfSR-4644.
【解决方案2】:

作为使用index(where:) 的替代方法,您可以使用带有for 循环的模式匹配来迭代匹配给定大小写的元素的索引,然后在第一个匹配时简单地使用break

var cells: [MessageCell] = [.from(""), .to(""), .subject(""), .to("")]

let recipient = "John"

for case let (offset, .to) in cells.enumerated() {
    cells[offset] = .to(recipient)
    break
}

print(cells) 
// [MessageCell.from(""), MessageCell.to("John"),
//  MessageCell.subject(""), MessageCell.to("")]

【讨论】:

    【解决方案3】:

    这是一个简化的演示,说明如何解决此问题,以便您了解其工作原理:

    var arr = ["a", "b"] // a, b
    if let index = arr.index(where: { $0 == "a" }) {
        arr[index] = "c"
    }
    print(arr) // c, b
    

    在你的情况下:

    if let index = cells.index(where: { if case .to = $0 { return true } else { return false } }) {
        cells[index] = .to(recipient)
    }
    

    【讨论】:

      【解决方案4】:

      试试这个:

      if let index = cells.index(where: { (messageCell) -> Bool in
                  switch messageCell
                  {
                  case .to(let x):
                      return x == recipient ? true : false
                  default:
                      return false
                  }
              })
              {
                  cells[index] = .to(recipient)
              }
      

      【讨论】:

        猜你喜欢
        • 2022-12-21
        • 2011-09-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多