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

Swift 如何获取数组中枚举大小写的索引,swift,enums,Swift,Enums,我需要更新存储在数组中的Enum的关联值。如何在不知道其索引的情况下访问适当案例的单元格 enum MessageCell { case from(String) case to(String) case subject(String) case body(String) } var cells = [MessageCell.from(""), MessageCell.to(""), MessageCell.subject(""), MessageCell.bo

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

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

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)
}

使用
if 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)")
}
输出:


作为使用
索引(其中:)
的替代方法,您可以将模式匹配与
for
循环一起使用,以迭代与给定情况匹配的元素的索引,然后在第一次匹配时简单地
中断

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("")]

看看这个,它吸吮关闭必须是如此复杂;查阅
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("")]