[英]Add / Update custom object dictionaries array in swift 4
我有一個帶有自定義對象的字典數組。 現在,我正在比較要添加和更新的對象。 邏輯很簡單:如果不存在則添加數據,如果字典中有任何更改則更新。
用戶是自定義對象類型:
@objc public class User: NSObject , Mappable
從getUserID我可以獲取userID
下面的代碼在for循環中從我傳遞User對象的位置執行。
var peopleList = [User]()
if self.peopleList.count > 0 {
if self.peopleList.contains(where: {$0.getUserID() == users.getUserID()})
{
// check for any update in dist
if let index = self.peopleList.index(of: users)
{
if users.isEqual(self.peopleList[index])
{
print("equal no updates")
}
else
{
print("need to updates objects..")
}
}
//already exist room
}
else
{
self.peopleList.append(users)
}
}
我知道這可能與平等
所以我用下面的功能
func isEqual<T: Equatable>(type: T.Type, a: Any, b: Any) -> Bool? {
guard let a = a as? T, let b = b as? T else { return nil }
return a == b
}
但是我得到index = nil.
有什么想法或建議來解決。 如果有其他有效的方式來做,他們將非常歡迎。
我認為這個簡化的版本應該可以工作
if self.peopleList.isEmpty, let user = self.peopleList.first(where: { $0.getUserID() == users.getUserID() }) {
if user == users {
// is equal
} else {
// do update
}
} else {
self.peopleList.append(users)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.