我有一个customObject
存储在 Firebase 的实时数据库中:
struct CustomObject: Codable {
var id: UUID?
var name: String?
var status: String?
}
customObjects
存储在aDictionary
中UUID
:key
我能够将数据加载到[String: CustomObject]
Dictionary
我的 iOS 应用程序中的 a 中,但我不确定我customObjects
使用 a进行排序和显示的方法List()
ForEach(...) {
是否是最佳实践。
我目前的解决方案是在加载Array
时构建Dictionary
每次数据库更新时,我都会使用重新didSet
创建一个可以在以下位置使用的:Array
list()
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.name
alist
和 a进行排序Dictionary
是不合适的。
根据苹果的文档
字典在没有定义排序的集合中存储相同类型的键和相同类型的值之间的关联。每个值都与一个唯一键相关联,该键充当字典中该值的标识符。与数组中的项目不同,字典中的项目没有指定的顺序。当您需要根据标识符查找值时,您可以使用字典,这与使用现实世界的字典查找特定单词的定义的方式非常相似。
使用并从中didSet
制作一个被认为是最佳实践吗?Array
Dictionary
customObjects
sorting
对于 a和listing
customObjects
从 a有更好的方法Dictionary
吗?