如何检查枚举与值的相等性

时间:2018-08-10 12:04:09

标签: ios swift

我有以下枚举:

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

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

我创建了一个枚举数组,如:

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

我想做的是检查options数组是否包含.share枚举(与它关联的类型无关),然后将其替换为另一类型的.share枚举。

例如

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

我该怎么做?

2 个答案:

答案 0 :(得分:1)

如果您要同时访问数组索引和对象,则可以将for caseoptions数组一起使用。

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
}

答案 1 :(得分:0)

他是把戏:

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