Swift / SwiftUI 独特的字典值

问题描述 投票:0回答:1

我在从 API 接收的字典中生成不同的变量列表时遇到了挑战。

收到的数据是一个数组:

struct ContactDetails: Codable, Hashable, Identifiable {
    var id = UUID()
    var company, name, email, phone, mobile, city, region: String
}

我在视图中显示数据,如下所示:

let results = ...array of the ContactDetails received
        if results != nil {
            List {
                ForEach(results ?? [], id: \.self) { result in
                    NavigationLink(destination: ProjectContactDetailsView(company: result.company, results: results ?? [])) {
                        Text(result.company)
                            .tag(result.id)
                    }
                }
            }
        }

在很多情况下,我会收到 30 到 40 个这样的结果,其中一些是来自同一家公司的联系人。正如您所看到的,我正在链接到一个新视图,其中包含基于公司名称的更多详细信息,我将在其中列出个人。如何减少或获得清晰的公司名称列表?

我已经尝试过:

使用扩展:

extension Sequence where Iterator.Element: Hashable {
    func unique() -> [Iterator.Element] {
        var seen: Set<Iterator.Element> = []
        return filter { seen.insert($0).inserted }
    }
}

但是我无法正确排序:

ForEach(results ?? [], id: \.self) { result in
                   ForEach(result.company.unique()) { company in
                       NavigationLink(destination: ProjectContactDetailsView(company: result.company, results: results ?? [])) {
                           Text(result.company)
                               .tag(result.id)
                       }
                   }
               }

有什么想法吗?

arrays swift dictionary swiftui swiftui-list
1个回答
0
投票

如果我理解正确,您只想从列表中删除重复项并显示唯一公司? 我已完成以下操作:

  1. 我使用接收到的

    ContactDetails
    数组创建了公司的计算变量:

    @State private var results: [ContactDetails] = [
        .init(company: "AMD", name: "", email: "", phone: "", mobile: "", city: "", region: ""),
        .init(company: "Apple", name: "", email: "", phone: "", mobile: "", city: "", region: ""),
        .init(company: "NVIDIA", name: "", email: "", phone: "", mobile: "", city: "", region: ""),
        .init(company: "NVIDIA", name: "", email: "", phone: "", mobile: "", city: "", region: ""),
        .init(company: "Paypal", name: "", email: "", phone: "", mobile: "", city: "", region: ""),
        .init(company: "AMD", name: "", email: "", phone: "", mobile: "", city: "", region: ""),
    ]
    
    var allCompanies: [String] {
        results.map({ $0.company }).unique()
    }
    

映射
所有公司之后,我使用了您的unique函数来生成一系列独特公司,如您所见。

然后你可以像这样使用它:

var body: some View {
    NavigationStack {
        ForEach(allCompanies, id: \.self) { result in
            NavigationLink(result) {
                Text(result)
            }
        }
    }
}

这是屏幕上的结果:

如果这是您想要的或者我误解了什么,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.