You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift List按药物类别分组:解决重复Section问题

药物按类别分组到Section的问题及解决方案

问题

尝试将药物按类别归类到对应的Section中,但添加同类药物时会出现多个重复的Section,不清楚使用model macros时该流程有何差异。

当前错误实现

这段代码会为每一个药物生成独立的Section,导致同类药物的Section标题重复出现:

List {
    ForEach(activeStash) { drug in
        Section(header: Text(drug.substanceClass)) {
            NavigationLink(destination: StashLinkView(stashed: drug)) {
                Text(drug.substance)
            }
        }
    }
}

错误的分组尝试

尝试嵌套ForEach但逻辑错误,不仅Section标题仍重复,每个Section下还会显示所有药物:

List {
    ForEach(activeStash) { drug in
        Section(header: Text(drug.substanceClass)) {
            ForEach(activeStash) { drug in
                NavigationLink(destination: StashLinkView(stashed: drug)) {
                    Text(drug.substance)
                }
            }
        }
    }
}

正确解决方案

先提取所有唯一的药物类别,再为每个类别生成对应的Section,最后在Section内筛选并显示该类别的所有药物:

List {
    ForEach(Array(Set(activeStash.map { $0.substanceClass })), id: \.self) { substanceClass in
        Section(header: Text(substanceClass)) {
            ForEach(activeStash.filter { $0.substanceClass == substanceClass }) { drug in
                NavigationLink(destination: StashLinkView(stashed: drug)) {
                    Text(drug.substance)
                }
            }
        }
    }
}

内容的提问来源于stack exchange,提问作者Defaced.Face

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 06:52:13