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

Swift中'self'在'self.init'调用前使用的错误修复咨询

修复Swift初始化错误:'self' used before 'self.init' call

问题分析

你遇到的错误源于违反Swift初始化规则:便利初始化器必须先调用指定初始化器完成实例初始化,之后才能访问或修改self的属性。同时代码存在冗余操作——协议初始化方法已传入id参数,无需再从字典中解析documentID。

修复步骤

  • 删除提前赋值的self.documentID = id语句
  • 从guard判断中移除冗余的documentID解析逻辑
  • 调用指定初始化器时,直接用传入的id参数初始化documentID
  • (规范优化)结构体名改为大写开头Employee,符合Swift命名习惯;将隐式解包属性改为非可选类型,避免潜在运行时崩溃

修正后的完整代码

import UIKit
import Firebase
import Firestore

protocol DocumentSerializable {
    init?(id: String, dictionary:[String:Any])
}

class Content {
}

struct Employee {
    var name: String
    var address: String
    var timeStamp: Date
    var documentID: String
    
    var dictionary:[String: Any] {
        return [
            "name": name,
            "address": address,
            "timeStamp": timeStamp,
            "documentID": documentID
        ]
    }
}

extension Employee : DocumentSerializable {
    init?(id: String, dictionary: [String : Any]) {
        guard let name = dictionary["name"] as? String,
              let address = dictionary["address"] as? String,
              let timeStamp = dictionary["timeStamp"] as? Date else {
            return nil
        }
        // 先调用指定初始化器完成实例初始化
        self.init(name: name, address: address, timeStamp: timeStamp, documentID: id)
    }
}

额外说明

  1. 修正了原代码中adress的拼写错误为address,避免字段匹配问题
  2. 将原隐式解包的name/address改为非可选类型,因guard已确保这两个值存在,无需隐式解包
  3. 修正协议名拼写为DocumentSerializable(原Seriziable拼写错误),符合标准命名规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 15:03:26