Home > database >  Cannot convert return expression of type '[String : Any]' to return type 'Song?'
Cannot convert return expression of type '[String : Any]' to return type 'Song?'

Time:02-10

Yes, this question has been posted a million times but none of the answers are helping my specific scenario. My project is running fine but this error keeps coming up and it's extremely annoying, especially since the project is running perfectly.

here is my Song struct

import Foundation
import SwiftUI

struct Song: Identifiable, Codable {
    var album: String
    var artist: String
    var description: String
    let id: String
    var title: String
}

Here is the class for getting data from Firestore (error is on line 31) Cannot convert return expression of type '[String : Any]' to return type 'Song?' and Argument passed to call that takes no arguments

import Foundation
import Firebase
import FirebaseFirestore
import FirebaseFirestoreSwift

class FirestoreManager: ObservableObject {
    @Published private(set) var songs: [Song] = []
    let db = Firestore.firestore()
    
    init() {
        fetchAllSongs()
    }
    
    func fetchAllSongs() {
        db.collection("Songs").addSnapshotListener { querySnapshot, error in
            guard let documents = querySnapshot?.documents else {
                print("Error")
                return
            }
            
            self.songs = documents.compactMap { document -> Song? in
                do {
                    print(document.data())
                    return try document.data(as: Song.self) // ERROR HERE
                } catch {
                    print("Error decoding document into Song: \(error)")

                    return nil
                }
            }
                
        }
    }
}

Can someone please tell me why this is happening? I have searched Google for hours and I'm following this course down to the tee. I even copy and pasted the source code and replaced what I needed to match my project. Thank you in advance.

CodePudding user response:

Your need to cast a [String:Any] to type Song which won't work you need

let res = document.data()
let album = res["album"] as! String 
let artist = res["artist"] as! String  
.....
let content=  Song(...
return content 
  • Related