I need to update associated value of Enum stored in an Array. How can I access the cell of the proper case without knowing its index?
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)
}
                Use if case to test for the enum case .to in the closure and return true if found, otherwise return false:
if let index = cells.index(where: { if case .to = $0 { return true }; return false }) {
    cells[index] = .to(recipient)
}
Here's a complete example:
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)")
}
Output:
.to found at index 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With