void 函数中出现意外的非空返回值

编程入门 行业动态 更新时间:2024-10-24 05:21:27
本文介绍了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 调用中返回 True 或 False,我会收到错误:non-void return value在 void 函数中

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 函数中出现意外的非空返回值

本文发布于:2023-11-26 18:31:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634699.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   返回值   意外   void

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!