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

Swift中Codable布尔枚举的JSON编码异常问题咨询

Bool类型枚举Codable编码异常修复

问题场景

以下代码中,SomeEnum是基于Bool类型的枚举并遵循Codable,但使用JSONEncoder编码SomeStruct实例时,实际输出为{"someEnum": {"true": {}}},而非预期的{"someEnum": true},希望仅修改SomeEnum代码(不影响其他使用场景)完成修复:

enum SomeEnum: Bool, Codable {
  case accept = true
  case reject = false
}

struct SomeStruct {
  var someEnum: SomeEnum
}

let s: SomeStruct = .init(someEnum: .accept)
print(String(data: try! JSONEncoder().encode(s), encoding: .utf8)!) 
// 实际输出: {"someEnum": {"true": {}}}
// 预期输出: {"someEnum": true}

问题原因

Swift默认的Codable合成逻辑对于无关联值的枚举,会将枚举case名称作为键、空对象作为值进行编码,而非使用枚举的原始值,这就导致了不符合预期的输出结构。

解决方案

只需在SomeEnum中手动实现Codable协议的编码/解码方法,强制使用枚举的rawValue(即Bool值)进行序列化,且该修改不会影响枚举在其他场景的使用:

enum SomeEnum: Bool, Codable {
    case accept = true
    case reject = false
    
    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encode(rawValue)
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        let rawValue = try container.decode(Bool.self)
        // 由于枚举已覆盖所有Bool可能值,强制解包安全
        self.init(rawValue: rawValue)!
    }
}

验证结果

修改后再次执行编码代码,输出将符合预期:{"someEnum": true}。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 10:20:00