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

如何使用children参数将字典数据展示为SwiftUI可折叠列表?

直接用字典配合List的children参数不可行,得换个方式实现

直接用你现有的字典结构没法直接通过List的children参数实现可折叠列表,原因有两个:

  1. 字典本身是无序的,版本列表通常需要按从新到旧排序,直接用字典会导致展示顺序混乱;
  2. List的children参数要求数据源元素是嵌套的可识别类型(遵循Identifiable协议,或能通过id参数指定唯一标识),而你的字典是键值对结构,每个元素的value是字符串数组,没法直接被children参数识别为子元素。

可行的实现方案

下面是两种常见的可折叠列表实现方式,都能满足你的需求:

方案一:用DisclosureGroup(兼容iOS13+)

这种方式更灵活,不需要修改太多数据结构:

  1. 先把字典转换成有序的模型数组
  2. 用DisclosureGroup包裹每个版本的特性列表
// 定义简单的模型,遵循Identifiable协议
struct VersionFeatures: Identifiable {
    let id = UUID()
    let version: String
    let features: [String]
}

// 你的原始字典数据
let featuresByVersion: [String : [String]] = [
    "1.2" : [
        "A new feature in this version",
        "Another new feature in this version.",
        "Etc.",
    ],
    "1.1" : [
        "A new feature in this version.",
        "Etc.",
    ],
]

// 将字典按版本号从高到低排序,转换成模型数组
let versionFeatures: [VersionFeatures] = featuresByVersion
    .sorted { $0.key > $1.key }
    .map { VersionFeatures(version: $0.key, features: $0.value) }

// 实现可折叠List
struct FeatureListView: View {
    var body: some View {
        List(versionFeatures) { version in
            DisclosureGroup("Version \(version.version)") {
                ForEach(version.features, id: \.self) { feature in
                    Text(feature)
                }
            }
        }
        .listStyle(.insetGrouped)
    }
}

方案二:用List的children参数(iOS15+)

如果一定要用children参数,需要把特性也改成遵循Identifiable的模型,让数据变成嵌套的可识别结构:

// 定义特性模型
struct Feature: Identifiable {
    let id = UUID()
    let text: String
}

// 定义版本模型,包含嵌套的特性数组
struct VersionFeatures: Identifiable {
    let id = UUID()
    let version: String
    let features: [Feature]
}

// 转换原始字典数据
let versionFeatures: [VersionFeatures] = featuresByVersion
    .sorted { $0.key > $1.key }
    .map { 
        VersionFeatures(
            version: $0.key, 
            features: $0.value.map { Feature(text: $0) }
        ) 
    }

// 使用children参数实现可折叠List
struct FeatureListView: View {
    var body: some View {
        List(versionFeatures, children: \.features) { item in
            // 根据元素类型展示不同内容
            if let version = item as? VersionFeatures {
                Text("Version \(version.version)")
            } else if let feature = item as? Feature {
                Text(feature.text)
            }
        }
        .listStyle(.insetGrouped)
    }
}

内容的提问来源于stack exchange,提问作者protasm

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 01:07:23