swiftif-statementlet

How to fix SwiftUI: Initializer for conditional binding must have Optional type, not 'ChatMessage'


I am a beginner in SwiftUI and I am trying to create a chat app with firestore. I have this issue and I looked many articles but I can't fix it. I'd be very happy if you help me! Thank you!

My Code:

func fetchMessages() {
        guard let fromId = FirebaseManager.shared.auth.currentUser?.uid else { return }
        guard let toId = chatUser?.uid else { return }
        firestoreListener?.remove()
        chatMessages.removeAll()
        firestoreListener = FirebaseManager.shared.firestore
            .collection(FirebaseConstants.messages)
            .document(fromId)
            .collection(toId)
            .order(by: FirebaseConstants.timestamp)
            .addSnapshotListener { querySnapshot, error in
                if let error = error {
                    self.errorMessage = "Failed to listen for messages: \(error)"
                    print(error)
                    return
                }
                
                querySnapshot?.documentChanges.forEach({ change in
                    if change.type == .added {
                        do {
                            if let cm = try change.document.data(as: ChatMessage.self) {
                                self.chatMessages.append(cm)
                                print("Appending chatMessage in ChatLogView: \(Date())")
                            }
                        } catch {
                            print("Failed to decode message: \(error)")
                        }
                    }
                })
                
                DispatchQueue.main.async {
                    self.count += 1
                }
            }
    }

The error I get is on this line:

if let cm = try change.document.data(as: ChatMessage.self) {

Error:

Initializer for conditional binding must have Optional type, not 'ChatMessage'

I have tried removing let, adding ? at the end of try but nothing works. If you need I can provide you with the full code, just help me. Im in a desperate sutiation.[[enter image description here](https://i.sstatic.net/oTTYoQwA.png)](https://i.sstatic.net/6JHftNBM.png)


Solution

  • Looks like the change.document.data(as:) method returns a type of ChatMessage and not an optional ChatMessage?. Therefore no need to unwrap it.

    Change the line to:

    let cm = try change.document.data(as: ChatMessage.self){
     ...