Tometoyou
Tometoyou

Reputation: 8376

How to check equality of enums with values

I have the following enums:

enum BulletinOption {
    case notifications
    case share(type: EventType)
}

enum EventType {
    case singleEvent(position: Int, text: String)
    case multipleEvents(text: String)
}

I create an array of enums like:

var options: [BulletinOption] = [
    .notifications,
    .share(type: .singleEvent(position: 8, text: "My text"))
]

What I want to do is check whether the options array contains the .share enum (doesn't matter about the type associated with it), and replace it with a different type of .share enum.

e.g.

if options.contains(BulletinOption.share) {
    // find position of .share and replace it 
    // with .share(type: .multipleEvents(text: "some text"))
}

How can I do that?

Upvotes: 3

Views: 80

Answers (2)

Nirav D
Nirav D

Reputation: 72410

If you want to access array index and object both then you can use for case with your options array.

for case let (index,BulletinOption.share(_)) in options.enumerated() {
    //Change value here
    options[index] = .share(type: .multipleEvents(text: "some text"))

    //You can also break the loop if you want to change for only first search object
}

Upvotes: 1

CZ54
CZ54

Reputation: 5588

He is the trick :

extension BulletinOption: Equatable {
   static func ==(lhs: BulletinOption, rhs: BulletinOption) -> Bool {
        switch (lhs, rhs) {
        case (.notifications, .notifications):
            return true
        case (.share(_), .share(_)):
            return true
        default:
            return false
        }
    } 

Upvotes: 0

Related Questions