0

我有一个customObject存储在 Firebase 的实时数据库中:

struct CustomObject: Codable {
    var id: UUID?
    var name: String?
    var status: String?
}

customObjects存储在aDictionaryUUIDkey

Firebase 词典截图

我能够将数据加载到[String: CustomObject] Dictionary我的 iOS 应用程序中的 a 中,但我不确定我customObjects使用 a进行排序和显示的方法List() ForEach(...) { 是否是最佳实践。

我目前的解决方案是在加载Array时构建Dictionary

每次数据库更新时,我都会使用重新didSet创建一个可以在以下位置使用的:Arraylist()

class AppManager: ObservableObject {

   @Published var customObjectArray: [CustomObject] = []

   @Published var customObjectDictionary: [String:CustomObject]? {
      didSet {
         if customObjectDictionary != nil {
            customObjectArray = []

            for (key, value) in customObjectDictionary! {
               var tempObject: CustomObject = value
               tempObject.id = UUID(uuidString: key)
               customObjectArray.append(tempObject)
            }

            customObjectArraySort()
         }
      }
   }
}

这是我的View

struct MainView: View {
    @EnvironmentObject var app: AppManager
    
    var body: some View {
        List {
            ForEach(app.customObjectArray.indices, id: \.self) { index in
                HStack{
                    Text(app.customObjectArray[index].name ?? "")
                    Spacer()
                    Text(app.customObjectArray[index].status ?? "")
                }
            }
        }
    }
}

我知道 aDictionary是一个无序的集合,并且尝试基于customObject.namealist和 a进行排序Dictionary是不合适的。

根据苹果的文档

字典在没有定义排序的集合中存储相同类型的键和相同类型的值之间的关联。每个值都与一个唯一键相关联,该键充当字典中该值的标识符。与数组中的项目不同,字典中的项目没有指定的顺序。当您需要根据标识符查找值时,您可以使用字典,这与使用现实世界的字典查找特定单词的定义的方式非常相似。

使用并从中didSet制作一个被认为是最佳实践吗?ArrayDictionarycustomObjects

sorting对于 a和listing customObjects从 a有更好的方法Dictionary吗?

4

1 回答 1

1

如果您想通过 ForEach 运行它,则必须将 aDictionary转换为 a符合的 a RandomAccessCollection,所以这很好。Array

无论您是否有Dictionary转换Array为数据源的 a,都不应.indices以这种方式使用,尤其是对于容易制作的东西Identifiable

struct MainView: View {
    @EnvironmentObject var app: AppManager
    
    var body: some View {
        List {
            ForEach(app.customObjectArray) { object in
                HStack{
                    Text(object.name ?? "")
                    Spacer()
                    Text(object.status ?? "")
                }
            }
        }
    }
}

struct CustomObject: Codable, Identifiable {
    var id: UUID // Make this non-optional
    var name: String?
    var status: String?
}

您设置它的方式,如果将任何元素添加到数组或从数组中删除,您可能会导致崩溃。这意味着你不能使用.onDelete,等等。而且,.onMove也不能正常工作。

于 2022-02-09T22:11:37.263 回答