【问题标题】:Filtering a For Each loop - swiftui过滤 For Each 循环 - swiftui
【发布时间】:2020-11-26 16:22:44
【问题描述】:

我是 SwiftUI 的新手,如果这是一个非常愚蠢的问题,我深表歉意,但我似乎无法弄清楚如何过滤我想通过部分 ID 或部分名称过滤数据的会话。非常感谢任何帮助!

let sessions = Bundle.main.decode([SessionsSection].self, from: "sessions.json")
    
    
var body: some View {
    
    //NavigationView {
        

        List {
            
            ForEach(sessions) { section in
                Section(header: Text(section.name)) {
                    
                    // Items in sections
                    ForEach(section.items) { item in
                        
                        ItemRow(item: item)
                    }
                }
                
            }
        } // List end bracket

【问题讨论】:

    标签: json list foreach swiftui


    【解决方案1】:

    你也可以filter 在 Swift 5 中使用键路径:

    extension SessionsSection {
      var isIncluded: Bool {
        return self.id >= 1 || self.name == "selection"
      }
    }
    
    ForEach(sessions.filter(\.isIncluded)) { section in
      // Insert code from above.
    }
    

    【讨论】:

    • 非常感谢!!这确实有效:)
    【解决方案2】:

    你可以在ForEach中使用.filter(_ :)函数

    ForEach(sessions.filter {
        $0.id == 0 //<< here comes your predicate, id or name. Return true if should be included
    }) { section in
    

    【讨论】:

    • 非常感谢!!不幸的是,因为我使用 UUID 格式作为 id,所以我不能使用这个:/ 除非,我误解了它..?
    猜你喜欢
    • 1970-01-01
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 2021-01-21
    • 2010-12-03
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    相关资源
    最近更新 更多