ios - 在 swift 4 中添加/更新自定义对象字典数组

标签 ios arrays swift dictionary

我在 swift 中有一个带有自定义对象的字典数组。 现在我正在比较添加和更新的对象。 逻辑很简单,如果不存在就添加数据,如果字典有任何变化就更新。

用户是自定义对象类型:

 @objc public class User: NSObject , Mappable  

从 getUserID 我可以得到 userID

下面的代码是在我传递 User 对象的地方的 for 循环中执行的。

 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)
    }
}

我知道可能和equatable有关

所以我正在使用下面的功能

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)
}

关于ios - 在 swift 4 中添加/更新自定义对象字典数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52016227/

相关文章:

ios - 在 for in 循环中修改数据结构是否安全?

ios - 分享 pdf 文档 .Swift

Java TicTacToe 游戏无法正确显示

ios - 从 UIViewController 调用自定义 UINavigationController 中的方法时目标错误

swift - 将结构传递给函数并在函数内创建该结构的实例

ios - polylineWithCoordinates 烦人的参数错误

jquery - 如何在 Kendo Ui Mobile 中将数据绑定(bind)到 Dropdownlist

c - 在C中将字符串拆分为数组

arrays - 向外行人解释数组的好处?

ios - Xcode Storyboard 中的对象消失