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

Swift枚举值无法含空格:如何将下划线替换为空格输出

解决方案

首先修正你代码里的一处错误:struct People 中的 code 类型应该是 PersonCodes(而非 PersonID),否则会因为类型不匹配导致解析失败。

接下来提供两种实用的实现方式,把枚举中的下划线替换为空格显示:

方法一:自动替换下划线(通用型)

给 PersonCodes 枚举添加一个计算属性,自动将枚举 case 名称里的下划线替换为空格,适合不需要特殊自定义显示文本的场景:

struct People: Decodable {
    var name: String
    var grade: String
    var code: PersonCodes // 修正类型错误
    
    enum PersonCodes: String, Decodable {
        case In_Transit = "0",
             Accepted = "1",
             Exception = "2",
             Delivered = "3"
        
        // 计算属性:替换下划线为空格
        var displayName: String {
            String(describing: self).replacingOccurrences(of: "_", with: " ")
        }
    }
}

使用方式:解析完成后,直接调用 displayName 属性即可得到格式化后的文本:

let jsonData = """
{
"name" : "Jake",
"grade" : "A Grade",
"code" : "0"
}
""".data(using: .utf8)!

do {
    let people = try JSONDecoder().decode(People.self, from: jsonData)
    print(people.code.displayName) // 输出:In Transit
} catch {
    print("解析错误:\(error)")
}

方法二:手动指定显示文本(灵活型)

如果某些枚举值的显示文本需要特殊处理(比如不是简单替换下划线),可以通过 switch 语句手动定义每个 case 的显示内容:

struct People: Decodable {
    var name: String
    var grade: String
    var code: PersonCodes
    
    enum PersonCodes: String, Decodable {
        case In_Transit = "0",
             Accepted = "1",
             Exception = "2",
             Delivered = "3"
        
        var displayName: String {
            switch self {
            case .In_Transit:
                return "In Transit"
            case .Accepted:
                return "Accepted"
            case .Exception:
                return "Exception"
            case .Delivered:
                return "Delivered"
            }
        }
    }
}

这种方式的优势在于可以自由定制每个枚举值的显示文本,不受枚举命名的限制。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 14:06:18