简体   繁体   English

Swift:根据保存在前端另一个创建的数组中的 ID 对从后端检索到的对象数组进行排序

[英]Swift: Sorting an array of objects retrieved from the backend based off their ids held in another created array in the frontend

I have created an array of ids that represents the order of objects that a user has reorganized the cells inside of a tableview.我创建了一个 id 数组,它表示用户在 tableview 中重新组织了单元格的对象的顺序。 I have saved this into the UserDefaults, as shown below.我已将其保存到 UserDefaults 中,如下所示。

let index = allAnimals.map { $0.id }
UserDefaults.standard.set(index, forKey:"sorted")

When the screen loads, it runs this function, which retrieves the objects from the backend and appends them to allAnimals.当屏幕加载时,它运行这个 function,它从后端检索对象并将它们附加到 allAnimals。

func getAllAnimals(barnId: String){
        let userid = UserDefaults.standard.string(forKey: "userid")!
        let params:[String:Any] = ["userid":userid,
                                   "barnid": barnId]
        
        print(Endpoint.getAllAnimals)
        print(params)
        
        showLoading()
        HTTPClient().post(urlString: Endpoint.getAllAnimals, params: params, token: nil) { [weak self](data, error) in
            self?.hideLoading()
            if(error != nil){
                print(error!.localizedDescription)
                return
            }
            if(error == nil && data != nil){
                let json = JSON(data!)
                print(json)
                let status = json["status"].stringValue
                if(status == "error"){
                    //self?.showAlert(message: json["message"].stringValue)
                    return
                }
                self?.allAnimals.removeAll()
                json["data"].array?.forEach({ (subJson) in
                    subJson["swines"].array?.forEach({ (swineJson) in
                        let animal = Animal(json: swineJson, type: "swine")
                        self?.allAnimals.append(animal)
                    })
                    subJson["cattles"].array?.forEach({ (cattleJson) in
                        let animal = Animal(json: cattleJson, type: "cattle")
                        self?.allAnimals.append(animal)
                    })
                    subJson["sheeps"].array?.forEach({ (sheepJson) in
                        let animal = Animal(json: sheepJson, type: "sheep")
                        self?.allAnimals.append(animal)
                    })
                    subJson["goats"].array?.forEach({ (goatJson) in
                        let animal = Animal(json: goatJson, type: "goat")
                        self?.allAnimals.append(animal)
                    })
                })
                print(self?.allAnimals.map { $0.id } as Any)
                self?.tableView.reloadData()
            }
        }
    }

I want to reorder the objects by their id, which is represented by the index array I have saved into UserDefaults, but currently when it reloads it is ordered by id by default through the backend.我想通过它们的 id 重新排序对象,它由我保存到 UserDefaults 中的索引数组表示,但目前当它重新加载时,它默认通过后端按 id 排序。 How can I reorder the tableview based on this new array of ids that I have created?如何根据我创建的这个新的 id 数组重新排序 tableview? I have played around with.sort() but cannot figure it out.我玩过 .sort() 但无法弄清楚。 Also, the function in the backend is not specifying how to order the array, it just by default grabs them by id ascending.此外,后端的 function 没有指定如何对数组进行排序,它只是默认通过 id 升序来获取它们。

You don't tell us what you save to UserDefaults.您没有告诉我们您保存到 UserDefaults 的内容。 If there is an ID field in the data that you download, you could save an array of those IDs to userDefaults in the order the user put them in.如果您下载的数据中有一个 ID 字段,您可以按照用户输入的顺序将这些 ID 的数组保存到 userDefaults。

You could then:你可以:

Read the array of IDs from UserDefaults.从 UserDefaults 中读取 ID 数组。 Let's call this sortedIDs我们称之为sortedIDs

Read the array of items from the back-end.从后端读取项目数组。 Let's call this array ServerStructsArray我们称这个数组ServerStructsArray

Assuming the records you read are structs named ServerStruct :假设您读取的记录是名为ServerStruct的结构:

struct ServerStruct {
    let id: Int  //Assume the ID is an Int. 
    //whatever fields
    let value1: String
}

In the completion handler of the network read:在网络的完成处理程序中读取:

Convert the array of the full records to a dictionary with the ID as the key:将完整记录的数组转换为以 ID 为键的字典:

var serverStructsDict = [Int : ServerStruct]()

for item in ServerStructsArray {
   serverStructsDict[item.key] = item
}

For each entry in the array from UserDefaults, get an ID and use it as a key to fetch an item from your dictionary of full records.对于来自 UserDefaults 的数组中的每个条目,获取一个 ID 并将其用作从完整记录字典中获取项目的键。 No need to sort again.无需再次排序。

If you do want to sort your array of items that you read from the back-end:如果您确实想对从后端读取的项目数组进行排序:

Assume that the dictionary of ServerStructs is called serverDict假设ServerStructs的字典叫做serverDict

let sortedArray: [ServerStruct] = sortedIDs.map { serverDict[$0]! }

You now have the records from the server restored to the order you saved to UserDefaults .您现在已将服务器中的记录恢复为您保存到UserDefaults的顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM