如何从完成处理程序返回一个值 [英] how to return a value from completion handler
本文介绍了如何从完成处理程序返回一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将从完成处理程序获得的值作为字符串放入文本视图,但出现错误.这是我尝试做的:
I want to put the value I get from the completion handler into Text view as a string, but I get an error. Here is what I try to do:
func final(name: String, completion: @escaping (_ message: String)-> Void){
guard let uid = AuthViewModel.shared.userSession?.uid else {return}
Firestore.firestore().collection("users").document(uid).collection("chats").document(name).collection("messages").whereField("read", isEqualTo: false).getDocuments { (snapshot, _) in
guard let documents = snapshot?.documents.compactMap({ $0.documentID }) else {return}
let unread = documents.count
let unreadString = String(unread)
completion(unreadString)
}
}
试着把它放在这样的文本中:
Try to put it in a text like so:
Text(model.final(name: name, completion: { (message) in
String(message)
}))
这是我得到的错误
Type '()' cannot conform to 'StringProtocol'; only struct/enum/class types can conform to protocols
推荐答案
对于简单的解决方案,使用一条消息 @State
var.并更新您的视图.这是演示
For simple solution use one message @State
var. and update your view.
Here is demo
struct ContentView: View {
@State private var message: String = ""
var body: some View {
Text(message)
.onAppear {
model.final(name: "Name") { message in
self.message = message
}
}
}
}
这篇关于如何从完成处理程序返回一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文