我有以下枚举:
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"))
}
我该怎么做?
答案 0 :(得分:1)
如果您要同时访问数组索引和对象,则可以将for case
与options
数组一起使用。
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
}
}