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

Swift中如何从StringOrInt枚举提取原始值而非关联值?

解决Swift Decodable解析多类型字段时获取原始字符串值的问题

问题场景

使用Swift的Decodable解析JSON时,某个字段的数据类型不固定,时而为Int类型、时而为String类型。已通过枚举StringOrInt实现了多类型解析,但打印该字段时会输出带枚举关联值的格式(如string("str")或int(0)),需要直接获取原始字符串形式的值(如"str"或"0")。

解决方案

给StringOrInt枚举添加CustomStringConvertible协议实现,自定义打印输出内容,即可直接得到目标格式的结果。修改后的完整代码如下:

enum StringOrInt: Decodable, CustomStringConvertible {
    case string(String)
    case int(Int)
    
    // 实现CustomStringConvertible协议,自定义打印输出
    var description: String {
        switch self {
        case .string(let str):
            return str
        case .int(let num):
            return String(num)
        }
    }
    
    init(from decoder: Decoder) throws {
        if let int = try? decoder.singleValueContainer().decode(Int.self) {
            self = .int(int)
            return
        }
        if let string = try? decoder.singleValueContainer().decode(String.self) {
            self = .string(string)
            return
        }
        
        throw Error.couldNotFindStringOrInt
    }
    
    enum Error: Swift.Error {
        case couldNotFindStringOrInt
    }
}

struct Properties: Decodable { // Swift类型名建议首字母大写,符合命名规范
    let name: StringOrInt
}

// 解析逻辑保持不变
let propData = feature.properties!
if let resData = try? JSONDecoder().decode(Properties.self, from: propData) {
    print(resData.name) // 现在会直接输出"str"或"0"这类原始值
}

说明

  • 通过实现CustomStringConvertible协议的description计算属性,根据枚举的关联值返回对应的字符串:
    • 若为.string类型,直接返回关联的字符串内容;
    • 若为.int类型,将整数转换为字符串后返回。
  • 调用print(resData.name)时,会自动使用description的返回值,输出你需要的原始字符串格式,而非带关联值的枚举格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 11:35:17