简体   繁体   中英

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.

eg

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

How can I do that?

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
}

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
        }
    } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM