提问者:小点点

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


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

共3个答案

匿名用户

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

匿名用户

作为使用index(where:)的替代方法,您可以将模式匹配与用于循环,以便遍历与给定情况匹配的元素的索引,然后在第一次匹配时简单地off

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