0

I have a custom object array of type LeaderboardUser(). This object contains a string variable of "uid", "email".

I am trying to make a statement to recognize if the uid given matches the uid of the LeaderBoard

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? I tried a contains() bool, but I don't know what and how how that works.

2
  • I am assuming that allFriends is the array containing elements of type LeaderboardUser? Commented Sep 30, 2020 at 6:18
  • Searching for the title of this question and the tag [swift] generated 800 hits, surely some should be helpful, find object in array Commented Sep 30, 2020 at 7:55

2 Answers 2

1

You just need to use contains(where: method here.

if self.allFriends.contains(where: { $0.uid == uidOfLeaderBoard }) {
    //...
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

@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:

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

        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.