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

Swift自定义Codable模型后无法调用属性构造器初始化实例怎么办

报错根因

你手动实现了Codable协议要求的init(from decoder: Decoder)初始化方法后,系统不会再自动为结构体生成带name、performance参数的默认成员初始化器。此时结构体只有接收Decoder类型参数的初始化方法,你直接传入字符串参数调用时,编译器找不到匹配的初始化方法,就会抛出参数类型不匹配、参数标签错误的报错。

另外你现有代码还存在两处隐性问题:

  • 解码performance属性时指定的解码类型是TextModel.self,和属性声明的String?类型不匹配,会导致解码永远返回nil
  • 创建实例时参数名拼写错误,将performance错写为perfdormace
修复方案

手动为结构体补充支持直接传参的成员初始化器,同时修正解码逻辑的类型错误,完整代码如下:

struct Student: Codable {
    let name: String?
    let performance: String?

    enum CodingKeys: String, CodingKey {
        case name, performance
    }

    // 自定义成员初始化器,支持直接传属性值创建实例
    init(name: String?, performance: String?) {
        self.name = name
        self.performance = performance
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        name = try container.decodeIfPresent(String.self, forKey: .name)
        // 修正解码类型,和属性类型保持一致
        performance = try container.decodeIfPresent(String.self, forKey: .performance)
    }
}

修正后即可按预期方式创建实例,注意修正参数名拼写:

let student = Student(name: "Bruce", performance: "A+")

补充提示:如果不手动实现init(from:),Swift在自动合成Codable协议实现时,会默认保留结构体的成员初始化器;一旦手动重写了解码初始化方法,默认成员初始化器会失效,需要手动补充实现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 14:27:18