Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert value of type 'x' to expected argument type '[String : Any]'

I'm currently attempting to create a user database, with Firestore in Swift 5.

I have created a signup view controller, and I am following the Firestore documentation (this link), in order to store the user data.


In a constants file I have stored the following code.

struct userMap: Codable {
    let firstName: String?
    let lastName: String?
    let email: String?
    let profilePictureURL: String?
    let UserIdentification: String?

    enum CodingKeys: String, CodingKey {
        case firstName
        case lastName
        case email
        case profilePictureURL
        case UserIdentification
    }
}

And in my signup view controller, I have this code.

let user = Constants.userMap(firstName: firstName,
                             lastName: lastName,
                             email: email,
                             profilePictureURL: metaImageURL,
                             UserIdentification: docRefID)

do {
    try dbRef.document(docRefID).setData(user)
} catch let error {
    print("Error writing to Firestore: \(error)")
}

On the line try dbRef.document(docRefID).setData(user) I am getting the error, "Cannot convert value of type 'Constants.userMap' to expected argument type '[String : Any]' "

Something I feel is worth adding. In the firebase documentation, it recommends the below.

try dbRef.document(docRefID).setData(from: user)

But, I tried this, and this too and I was just asked to remove from:.

Thanks all for your help.


1 Answers

You are using an object of the struct userMap instead of using a dictionary. You can fix this by creating a dictionary inside the userMap struct and providing that dictionary as the parameter. Since your struct already conforms to Codable you can create Data from object of userMap using JSONEncoder. Then you can convert the data to a JSON dictionary to use as a parameter. Here the code:

struct userMap: Codable {
    //...
    var dictionary: [String: Any] {
        let data = (try? JSONEncoder().encode(self)) ?? Data()
        return (try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any]) ?? [:]
    }
}

And for the setData:

try dbRef.document(docRefID).setData(from: user.dictionary)

Note: Main struct names capitalized for consistency So, convert userMap to UserMap.

like image 150
Frankenstein Avatar answered Feb 05 '26 11:02

Frankenstein