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

从Firestore获取Int类型数据失败,提示‘调用append的结果未被使用’问题求助

解决Firestore获取Int类型数据时的「Result of call to 'append' is unused」错误

咱们先拆解问题根源:你定义的point是单个整数类型的@Published属性(@Published var point = 0),但你错误调用了self.$point.append(points)——这里的$point是Combine框架的Publisher对象,append是给发布者添加事件的方法,它会返回一个新的Publisher但你没用到,所以编译器抛出了警告。更关键的是,更新单个Int值完全不需要append,直接给point赋值即可,@Published会自动把值的变化同步给订阅者。

下面是修正后的代码,同时优化了可选值的安全处理(避免强制解包导致崩溃):

class PointsModel: ObservableObject { 
    @Published var point = 0 
    
    init() { 
        let db = Firestore.firestore() 
        guard let userId = Auth.auth().currentUser?.uid else {
            print("用户未登录,无法获取数据")
            return
        }
        
        db.collection("Male").document(userId).getDocument { (snap, error) in 
            if let error = error {
                print("Firestore数据获取失败: \(error.localizedDescription)")
                return
            }
            
            guard let document = snap, document.exists else {
                print("对应用户的文档不存在")
                return
            }
            
            // 从文档中解析Coins字段,解析失败时默认值为0
            let points = document.get("Coins") as? Int ?? 0
            // 直接赋值更新point,@Published会自动通知视图更新
            self.point = points
        } 
    } 
}

关键修正细节:

  • 替换self.$point.append(points)为self.point = points:因为point是单个Int变量,直接赋值就能更新它的值,@Published属性会自动把变化同步给所有订阅的视图。
  • 用guard let安全处理用户ID:避免强制解包user!,如果用户未登录会提前返回并打印提示,防止崩溃。
  • 新增文档存在性检查:如果Firestore中没有对应用户的文档,会打印明确提示,方便排查问题。
  • 完善错误信息:打印具体的错误描述,让调试更高效。

这样修改后,你就能成功从Firestore获取到Int类型的Coins数据,同时解决那个编译警告问题。

内容的提问来源于stack exchange,提问作者Batuhan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 23:39:08