首页 > 解决方案 > Can't seem to save local array in Swift

问题描述

So I'm running into a problem where I can't seem to save the contents of a local array outside of a for loop. This code iterates through notifsTop (which is a dictionary) and saves the values into another array. However, outside of the for loop, the contents of tempnotifsarray are empty, which doesn't make sense to me since I appended them to an array that is outside of the loop block. I have been struggling with this for some time and can't figure out what is going on. Any help would be appreciated, thanks!

func createArray() -> [notificationLabel] {

        let newUserInfo = Auth.auth().currentUser
        let uid = newUserInfo?.uid
        self.ref = Database.database().reference()
        let practionerRef =  self.ref.child("users").child(uid!)

        var tempnotifsArray: [notificationLabel] = []





        practionerRef.observeSingleEvent(of: .value, with: {(snapshot) in

            let value = snapshot.value as? NSDictionary

            if let notifsTop = value?["Notifications"] as? NSDictionary { //top of the notifications hierarchy

                for (_, myValue) in notifsTop {
                    // Iterate in here
                    //self.notifications.append(myValue)

                    let notification = notificationLabel(label: myValue as! String)
                    tempnotifsArray.append(notification)

                    //if I print here the array is full with the values I want


                }
            }

        })


        print(tempnotifsArray) //comes out as []

        return tempnotifsArray

    }

标签: iosarraysswiftfirebase

解决方案


推荐阅读