Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get index of enum case in array

Tags:

enums

swift

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)
}
like image 964
Martin Koles Avatar asked Dec 02 '22 13:12

Martin Koles


1 Answers

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
like image 94
vacawama Avatar answered Mar 08 '23 11:03

vacawama