Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if array contains a specific enum type

Tags:

enums

ios

swift

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
        }
    }
like image 763
Cory Avatar asked Dec 07 '22 15:12

Cory


2 Answers

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
})
like image 173
Dávid Pásztor Avatar answered Dec 15 '22 01:12

Dávid Pásztor


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
}
like image 37
Adamsor Avatar answered Dec 14 '22 23:12

Adamsor