返回数组时,void函数中出现非预期的非无效返回值 [英] Unexpected non-void return value in void function when returns an array

查看:76
本文介绍了返回数组时,void函数中出现非预期的非无效返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想寻求帮助,因为我真的很困惑.当它返回一个数组时,它说"void函数中非预期的非void返回值".我认为我的问题是括号,但我不知道如何解决.

I would like to get help cuz I'm really confused. It says "Unexpected non-void return value in void function" when it returns an array. I think that my problem is brackets, but I don't know how to fix it.

func getWords() -> Array<Any>{

           ref = Database.database().reference()
            ref.child("addedWords").observe(.value, with: { (DataSnapshot) in
                var tempWords = DataSnapshot.value as! [String:AnyObject]
                var words = Array(tempWords.keys)
                print(words)

                return words
                })}

推荐答案

您不能只在 closures 中返回 words .首先,这是一个异步方法,其次,您需要在闭包之外返回一个值,该值将在闭包之前被调用.您需要具有 completionHandler ,而不是返回 Array< Any> .在这种情况下,如果成功,则可以传递该值.像这样:

You can´t just return words in your closure. First of all it´s an async method second you need to return a value outside of the closure which will be called before the closure. You need to have a completionHandler instead of returning Array<Any>. In that case you can pass the value if and when it succeeds. Something like this:

func getWords(onCompletion: @escaping (Array<Any>) -> Void) {
    ref = Database.database().reference()
    ref.child("addedWords").observe(.value, with: { (DataSnapshot) in
        var tempWords = DataSnapshot.value as! [String:AnyObject]
        var words = Array(tempWords.keys)
        print(words)
        onCompletion(words)
    })
}

调用它:

getWords(onCompletion: { (words) in
    print(words)
})

这篇关于返回数组时,void函数中出现非预期的非无效返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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