[英]How to check equality of enums with values
我有以下枚举:
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"))
}
我怎样才能做到这一点?
如果要访问数组索引和对象,则可以使用options
数组的for case
。
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
}
他是诀窍:
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.