I want to extract random UIDs in RealtimeDatabase as an array.

I want to put this lower UID written as one person (this UID is a dummy made appropriately) into the array and take it out at random, but I can't understand it even after reading the official Firebase documentation.

For existing code,

var uids: Array? = []
    func matchDatabase () {
        ref = Database.database (). reference ()
        // bring one person's data from the database
        ref.child ("field"). child ("1 person"). observe (DataEventType.childAdded, with: {(snapshot)->Void in
            let snapshotkey = snapshot.key as! NSDictionary
            let uid = snapshotkey as! String
            // store uid in array
            self.uids? .append (uid)
            // randomly extract uid from uids
            var index = arc4random (uids? .count)

var index = arc4random (uids? count)
An error has occurred in the part.
Both Swift and Firebase are completely new, so they are completely stuck ...

I would be happy if someone could tell me.

  • Answer # 1

    I'm not sure about RealtimeDatabase, so it's mainly about Swift.
    That alone has some problems.

    arc4random ()is a function that takes no arguments. It takesarc4random_uniform ()as an argument.

    arc4random_uniform ()argument type isUInt32, butuids? countisInt?type is.
    As is optional, Swift does not cast Int and UInt32 automatically because Swift is strict.

    Do I need to make

    uidsoptional or omit the array type parameter?
    Avoid unnecessary optional and ambiguous types. It is recommended to use[Type]instead ofArray.

    snapshot.key is a String type, right? Casting to NSDictionay and String will definitely fail and maybe unnecessary.

    If I solve the above problems, I would write

    var uids: [String] = []
    func matchDatabase () {
    // Abbreviation
        let uid = snapshot.key
        // store uid in array
        self.uids.append (uid)
        // randomly extract uid from uids
        var index = arc4random_uniform (UInt32 (uids.count))
    // Abbreviation

Related articles