gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-10-31 23:56:17 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com