[英]Find Object in Object Array Swift
I have a custom object array of type LeaderboardUser()
.我有一个LeaderboardUser()
类型的自定义对象数组。 This object contains a string variable of "uid", "email".该对象包含一个字符串变量“uid”、“email”。
I am trying to make a statement to recognize if the uid given matches the uid of the LeaderBoard
我正在尝试声明以识别给定的 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)
}
Is there any way that I can search the UID parameter?有什么方法可以搜索 UID 参数吗? I tried a contains() bool, but I don't know what and how how that works.我尝试了 contains() bool,但我不知道它是什么以及如何工作。
You just need to use contains(where:
method here.您只需要contains(where:
此处使用contains(where:
方法。
if self.allFriends.contains(where: { $0.uid == uidOfLeaderBoard }) {
//...
}
Param of contents func is a closure that takes an element of the sequence as its argument and returns a Boolean value that indicates whether the passed element represents a match内容参数 func 是一个闭包,它将序列的一个元素作为其参数并返回一个布尔值,该值指示传递的元素是否表示匹配
@inlinable public func contains(where predicate: (Element) throws -> Bool) rethrows -> Bool
you can using it like:你可以像这样使用它:
if allFriends.contains(where: { (leaderboardUser) -> Bool in
return leaderboardUser.uid == idYouWantToFind
}) {
}
or with sort version:或使用排序版本:
if allFriends.contains(where: { $0.uid == idYouWantToFind}) {
}
and if you make your LeaderboardUser comfort to Equatable protocol, you can use like this:如果你让你的 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) {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.