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

SwiftUI中合并不同结构体数组并按日期排序展示方法

解决SwiftUI中不同结构体数组按日期合并排序的问题

步骤1:完善DateSortable协议

你代码中用到的DateSortable需要明确定义,保证两个结构体都能提供排序所需的日期属性:

protocol DateSortable {
    var date: Date { get }
}

步骤2:创建统一封装类型

由于两个结构体类型不同,我们需要一个容器来统一它们,使用枚举是最安全的方式:

enum SortedItem: Identifiable, DateSortable {
    case struct1(Struct1)
    case struct2(Struct2)
    
    // 实现Identifiable协议的id属性
    var id: UUID {
        switch self {
        case .struct1(let item): return item.id
        case .struct2(let item): return item.id
        }
    }
    
    // 实现DateSortable协议的date属性
    var date: Date {
        switch self {
        case .struct1(let item): return item.date
        case .struct2(let item): return item.date
        }
    }
}

步骤3:合并数组并按日期排序

在ContentView中定义两个结构体的数组,转换为统一的SortedItem数组后排序:

struct ContentView: View {
    // Struct1示例数据
    let struct1Array: [Struct1] = [
        Struct1(date: Date().addingTimeInterval(43200), property1: "第一个Struct1"),
        Struct1(date: Date().addingTimeInterval(259200), property1: "第二个Struct1")
    ]
    
    // Struct2示例数据
    let struct2Array: [Struct2] = [
        Struct2(date: Date(), property2: 10),
        Struct2(date: Date().addingTimeInterval(86400), property2: 20),
        Struct2(date: Date().addingTimeInterval(172800), property2: 30)
    ]
    
    // 合并并排序后的数组
    var sortedCombinedItems: [SortedItem] {
        let combined = struct1Array.map(SortedItem.struct1) + struct2Array.map(SortedItem.struct2)
        return combined.sorted { $0.date < $1.date } // 升序排序,降序则改为`>`
    }
    
    var body: some View {
        ScrollView {
            VStack(alignment: .leading, spacing: 10) {
                ForEach(sortedCombinedItems) { item in
                    // 根据类型渲染对应UI
                    switch item {
                    case .struct1(let struct1Item):
                        VStack(alignment: .leading) {
                            Text("Struct1 条目")
                                .font(.headline)
                            Text("ID: \(struct1Item.id.uuidString.prefix(8))")
                            Text("日期: \(struct1Item.date.formatted(date: .abbreviated, time: .shortened))")
                            Text("Property1: \(struct1Item.property1)")
                        }
                        .padding()
                        .background(Color.blue.opacity(0.2))
                        .cornerRadius(10)
                        
                    case .struct2(let struct2Item):
                        VStack(alignment: .leading) {
                            Text("Struct2 条目")
                                .font(.headline)
                            Text("ID: \(struct2Item.id.uuidString.prefix(8))")
                            Text("日期: \(struct2Item.date.formatted(date: .abbreviated, time: .shortened))")
                            Text("Property2: \(struct2Item.property2)")
                        }
                        .padding()
                        .background(Color.gray.opacity(0.2))
                        .cornerRadius(10)
                    }
                }
            }
            .padding()
        }
    }
}

关键说明

  • 枚举封装既保证类型安全,又能统一处理排序和渲染逻辑
  • 直接利用DateSortable协议的date属性完成排序,逻辑简洁清晰
  • 在ForEach中通过switch判断枚举类型,分别渲染对应结构体的专属UI,适配不同数据结构的展示需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 17:10:19