how do you use swift to return a dictionary?

The result inside your fetch(childpath:) method is set asynchronously, you cannot use return in this case – you’ll always return nil because the value is not set “on the fly”.

What you should do is pass a closure as the second parameter to this method and call it when you wish to notify of the method’s completion. Try this:

func fetch(childpath:String, completion: @escaping (NSDictionary?) -> Void) {
    let firebaseUID = Auth.auth().currentUser?.uid
    let ref = Database.database().reference()
    let path = childpath.replacingOccurrences(of: "uid", with: firebaseUID!)
    var children = [String]()
    var childrenPath = path.split(separator: "/")
    let childref = ref.child("\(childrenPath[0])").child("\(childrenPath[1])")
    childref.observeSingleEvent(of: .value, with: { (snapshot) in
        let value = snapshot.value as? NSDictionary
    }) { (error) in

And now you use the method like this:

FirebaseManager().fetch(childpath: "customers/uid") { result in
    if let result = result {
        // use your dictionary

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top