[英]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. 我想要做的是检查options数组是否包含
.share
枚举(与其关联的类型无关),并将其替换为不同类型的.share
枚举。
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. 如果要访问数组索引和对象,则可以使用
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
}
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.