Swift与Firebase报错求助:Value of type User has no member asDict()
Hey there! I see where the issue is—let's get this sorted out quickly so you can save your user data to Firebase without problems.
The Core Problem
Your UserClass struct doesn't conform to the Encodable protocol, but your asDict() method is an extension on Encodable. That's why the compiler can't find the asDict() method when you try to call it on a UserClass instance.
Step 1: Make UserClass Conform to Encodable
Update your UserClass definition to add the Encodable conformance. Since all your struct's properties (String, [String]) are already encodable, Swift will automatically generate the required encoding logic for you:
struct UserClass: Encodable { var uid: String var email: String var profileImageUrl: String var username: String var searchName: [String] var description: String }
Step 2: Improve Error Handling (Optional but Recommended)
Right now you're using try? which silently ignores errors if the conversion fails. To make debugging easier, switch to a do-catch block so you can pass meaningful error messages to your onError handler:
// Replace this line: // guard let dict: [String: Any] = try?user.asDict() else {return} // With this: do { let dict = try user.asDict() firestoreUserId.setData(dict) { error in if let error = error { onError(error.localizedDescription) return } } onSuccess(user) } catch { onError("Failed to convert user to dictionary: \(error.localizedDescription)") return }
Why This Works
The JSONEncoder (used in your asDict() extension) only knows how to encode types that follow the Encodable protocol. By adding that conformance to UserClass, you're telling Swift how to turn your struct into JSON data, which your extension then converts into a dictionary for Firebase.
That should fix the error you're seeing! Let me know if you run into any other bumps along the way.
内容的提问来源于stack exchange,提问作者Johnusz

