What is the best way to determine if an array of enum types contains a specific enum type, the kicker is the enum cases have associated types
for example, with the following data structure, how would I get the first video
let sections = [OnDemandSectionViewModel]
public struct OnDemandSectionViewModel: AutoEquatable {
public let sectionStyle: SectionHeaderStyle
public let sectionItems: [OnDemandItemType]
public let sectionType: SectionType
}
public enum OnDemandItemType: AutoEquatable {
case video(VideoViewModel)
case button(ButtonViewModel)
case game(GameViewModel)
case collectionGroup(CollectionGroupViewModel)
case clip(ClipViewModel)
}
I'm trying to find the first video, currently, I'm doing the following, but was curious if there is a better way
for section in sections {
for item in section.sectionItems {
switch item {
case .video(let video):
print("This is the first video \(video)")
return
default: break
}
}
You can use Sequence.first(where:)
, which is pretty much like contains(where:)
, but instead of simply returning a bool, it returns the first element satisfying the condition in the closure or nil
if there's no such element.
let firstVideo = sections.sectionItems.first(where: { item in
if case .video = item {
return true
}
return false
})
If you don't need VideoViewModel
contained in enum it's enough to type
if section.sectionItems.contains(where: { item in
if case .video = item {
return true
}
return false
}) {
// Your section contains video
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With