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