void函数中的异常非无效返回值-Swift 4(Firebase,Firestore) [英] Unexpected non-void return value in void function - Swift 4 (Firebase, Firestore)

查看:148
本文介绍了void函数中的异常非无效返回值-Swift 4(Firebase,Firestore)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想要一个布尔函数,该布尔函数根据给定的电子邮件是否存在给users集合中的用户,返回true或false.

So I want a Boolean function that returns true or false depending on whether the given email exists for a user in the users collection.

但是,如果我尝试在getDocuments调用中返回TrueFalse,则会出现错误:non-void return value in void function

However if I try and return True or False within the getDocuments call I get the error: non-void return value in void function

func checkUserWith(email: String) -> Bool
{
    let usersDB = database.collection("users")
    usersDB.whereField("email", isEqualTo: email).getDocuments { (snapshot, error) in

        if error != nil
        {
            print("Error: \(error?.localizedDescription ?? "")")
            return false
        }

        for document in (snapshot?.documents)! {
            if document.data()["email"]! as! String == email {
                return true
            }
        }

        return false
    }
}

我有一种感觉,是因为我试图在Firestore调用中返回一个布尔值,而该布尔值期望一个不同的变量类型?

I have a feeling it is because I am trying to return a boolean within the Firestore call which is expecting a different variable type?

推荐答案

由于firebase操作为您提供了回调闭包,并且调用是异步进行的,因此我相信您不可能直接从闭包中返回.但是,您可以按如下所示返回转义的闭包,指示true或false ...

Since the firebase operation gives you a callback closure, and the calls made asynchronously, I believe it wont be possible for you to directly return from closures. However, you can return an escaping closure indicating true or false as follows...

func checkUserWith(email: String, completion: @escaping (Bool) -> Void)
{
    let usersDB = database.collection("users")
    usersDB.whereField("email", isEqualTo: email).getDocuments { (snapshot, error) in

        if error != nil
        {
            print("Error: \(error?.localizedDescription ?? "")")
            completion(false)
        }

        for document in (snapshot?.documents)! {
            if document.data()["email"]! as! String == email {
                completion(true)
                return
            }
        }

        completion(false)
    }
}

然后,当您调用此方法时:

Then when you call this method:

checkUserWith(email: emailHere) { (isSucceeded) in
    if isSucceeded {
        //it exists, do something
    } else {
        //user does not exist, do something else
    }
}

这篇关于void函数中的异常非无效返回值-Swift 4(Firebase,Firestore)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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