确定枚举类型数组是否包含特定枚举类型的最佳方法是什么,最重要的是枚举案例具有关联类型
例如,使用以下数据结构,我将如何获得第一个视频
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)
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试找到第一个视频,目前,我正在执行以下操作,但是很好奇是否有更好的方法
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
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用Sequence.first(where:),它非常像contains(where:),但它不是简单地返回一个 bool,而是返回满足闭包中条件的第一个元素,或者nil如果没有这样的元素。
let firstVideo = sections.sectionItems.first(where: { item in
if case .video = item {
return true
}
return false
})
Run Code Online (Sandbox Code Playgroud)
如果您不需要VideoViewModel包含在枚举中,则输入就足够了
if section.sectionItems.contains(where: { item in
if case .video = item {
return true
}
return false
}) {
// Your section contains video
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6351 次 |
| 最近记录: |