7

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
        }
    }
1
  • Even you can use contains array property. It is far much better than this. Commented Feb 8, 2018 at 13:43

3 Answers 3

11

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
})
Sign up to request clarification or add additional context in comments.

1 Comment

This has the advantage of working nice with associated values.
7

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
}

Comments

1

Using filter function example:

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

Or

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.