无法返回在函数Swift中创建的数组 [英] Cannot Return an array created within a function Swift

查看:49
本文介绍了无法返回在函数Swift中创建的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个奇怪的问题,我不确定自己做错了什么.

I have an odd issue and I’m not sure what I am doing wrong.

我想在viewDidLoad中调用以下函数,以从Firestore加载将在表格视图中显示的集合中的所有文档.

I have the following function that I want called in viewDidLoad to load all documents in a collection from Firestore that will be displayed in a tableview.

func functionName() -> [String] {

    var NameArray = [String]()

    db.collection("Names").getDocuments() { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
            for document in querySnapshot!.documents {
                NameArray.append("\(document.documentID)")
            }
        }
    }
    print(NameArray)
    print(NameArray.count)

    return (NameArray)
}

该函数将发出警告结果被忽略.我不想因为需要该值而使其静音,它应该返回一个包含文档名称的数组.

The function throws a warning result is being ignored. I don’t want to silence it as I need the value, it should return an array with the document names.

当我尝试下面的代码时,它返回数组并按预期计数.

When I tried the below code, it returns the array and count as expected.

@IBAction func fetchUsersButton(_ sender: UIButton) {
    var NameArray = [String]()

    db.collection("Names").getDocuments() { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
            for document in querySnapshot!.documents {
                NameArray.append("\(document.documentID)")
            }
        }
        print(NameArray)
        print(NameArray.count)
    }
}

但是,我需要能够返回创建的数组,以便可以在函数外部使用它.有人可以帮忙吗?

However, I need to be able to return the array created so it can be used outside the function. Is anyone able to help?

推荐答案

代替返回数组,您需要将其放置在完成处理程序中.

Instead of returning an array you need to place it in a completion handler.

func functionName(_ completion: @escaping ([String]) -> Void) {

    var NameArray = [String]()

    db.collection("Names").getDocuments() { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
            for document in querySnapshot!.documents {
                NameArray.append("\(document.documentID)")
            }
        }

        completion(NameArray)
    }        
}

这篇关于无法返回在函数Swift中创建的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆