【问题标题】:how to return a value from completion handler如何从完成处理程序返回一个值
【发布时间】:2021-07-31 00:18:47
【问题描述】:

我想将从完成处理程序中获得的值作为字符串放入 Text 视图中,但出现错误。这是我尝试做的:

    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)
        }
    }

试着把它写成这样的文本:

Text(model.final(name: name, completion: { (message) in
 String(message)
 }))

这是我得到的错误

Type '()' cannot conform to 'StringProtocol'; only struct/enum/class types can conform to protocols

【问题讨论】:

  • 您已声明完成处理程序返回 Void 因此错误,将返回类型更改为 String
  • 并使completion(unreadString)return completion(unreadString) 一样显式返回

标签: swift swiftui completionhandler


【解决方案1】:

对于简单的解决方案,请使用一条消息@State var。并更新您的观点。 这是演示

struct ContentView: View {
    
    @State private var message: String = ""
    
    var body: some View {
        Text(message)
            .onAppear {
                model.final(name: "Name") { message in
                    self.message = message
                }
            }
    }
}

【讨论】:

    猜你喜欢
    • 2019-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-07
    • 2019-01-24
    相关资源
    最近更新 更多