Cory
Cory

Reputation: 2312

Check if array contains a specific enum type

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

Upvotes: 7

Views: 11608

Answers (3)

patilh
patilh

Reputation: 73

Using filter function example:

return section.filter({ $0.sectionType == .video }).first != nil 

Or

return section.filter( { $0.sectionType == .video }).count ?? 0 > 0

Upvotes: 1

David Pasztor
David Pasztor

Reputation: 54716

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

Upvotes: 11

Adamsor
Adamsor

Reputation: 770

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
}

Upvotes: 7

Related Questions