【问题标题】:Find Object in Object Array Swift在对象数组 Swift 中查找对象
【发布时间】:2021-01-15 18:28:43
【问题描述】:

我有一个LeaderboardUser() 类型的自定义对象数组。该对象包含一个字符串变量“uid”、“email”。

我正在尝试声明以识别给定的 uid 是否与 LeaderBoard 的 uid 匹配

if self.allFriends.contains() {
    // Remove user
    Database.database().reference().child("Users").child(Auth.auth().currentUser!.uid).child("Friends").child(self.uid).removeValue()
} else {
    // Add user
    let key = Database.database().reference().child("Users").childByAutoId().key
    let friends = ["uid" : "\(self.uid)"] as [String : Any]
    let totalList = ["\(key!)" : friends]
    Database.database().reference().child("Users").child(Auth.auth().currentUser!.uid).child("Friends").updateChildValues(totalList)
}

有什么方法可以搜索 UID 参数吗? 我尝试了 contains() bool,但我不知道它是什么以及如何工作。

【问题讨论】:

  • 我假设allFriends 是包含LeaderboardUser 类型元素的数组?
  • 搜索这个问题的标题和标签 [swift] 产生了 800 次点击,肯定有些应该有帮助,find object in array

标签: ios arrays swift search


【解决方案1】:

你只需要在这里使用contains(where:方法。

if self.allFriends.contains(where: { $0.uid == uidOfLeaderBoard }) {
    //...
}

【讨论】:

    【解决方案2】:

    内容参数 func 是一个闭包,它以序列的一个元素作为其参数,并返回一个布尔值,该值指示传递的元素是否表示匹配

    @inlinable public func contains(where predicate: (Element) throws -> Bool) rethrows -> Bool
    
    

    你可以像这样使用它:

            if allFriends.contains(where: { (leaderboardUser) -> Bool in
                return leaderboardUser.uid == idYouWantToFind
            }) {
    
            }
    

    或使用排序版本:

            if allFriends.contains(where: { $0.uid == idYouWantToFind}) {
    
            }
    

    如果您让 LeaderboardUser 对 Equatable 协议感到满意,您可以这样使用:

    class LeaderboardUser: Equatable {
        var uid: String = ""
        var email: String = ""
    
        static func == (lhs: LeaderboardUser, rhs: LeaderboardUser) -> Bool {
            return lhs.uid == rhs.uid
        }
    }
    
            if allFriends.contains(userWantToFind) {
    
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-13
      • 2017-04-15
      • 1970-01-01
      • 1970-01-01
      • 2011-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多