You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift与Firebase报错求助:Value of type User has no member asDict()

Fixing the 'Value of type User has no member asDict()' Error

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
}

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 15:22:45