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

Swift解码JSON时如何将单条ID字符串拆分为4个独立字段存储

Swift 固定长度ID字符串优雅拆分解析方案

实现思路

不需要修改你现有的泛型解码扩展,也不需要手动循环处理数据,只需要给新的Codes结构体自定义Decodable初始化方法,在解码阶段自动完成字符串拆分即可,完全兼容你现有所有调用逻辑。

完整Codes结构体实现

struct Codes: Codable, Identifiable {
    let id1: String    // 第1-3位(3位数字)
    let id2: String    // 第4位(1位数字)
    let id3: String    // 第5-6位(2位数字)
    let id4: String    // 第7-10位(4位数字)
    
    // Identifiable协议要求的id属性,直接用唯一的id4即可
    var id: String { id4 }
    
    // 自定义解码逻辑
    init(from decoder: Decoder) throws {
        // 直接解码出单条10位ID字符串
        let container = try decoder.singleValueContainer()
        let rawId = try container.decode(String.self)
        
        // 可选:增加长度校验,避免异常数据导致后续取值崩溃
        guard rawId.count == 10 else {
            throw DecodingError.dataCorruptedError(in: container, debugDescription: "ID长度不符合10位要求: \(rawId)")
        }
        
        // 按固定位置拆分字符串
        let startIndex = rawId.startIndex
        id1 = String(rawId[startIndex..<rawId.index(startIndex, offsetBy: 3)])
        id2 = String(rawId[rawId.index(startIndex, offsetBy: 3)])
        id3 = String(rawId[rawId.index(startIndex, offsetBy: 4)..<rawId.index(startIndex, offsetBy: 6)])
        id4 = String(rawId.suffix(4))
    }
}

使用方法

你原来的Bundle扩展代码不需要做任何修改,调用方式也和之前完全一致:

let codes: [Codes] = Bundle.main.decode(file: "codes.json")

可选优化(非必须)

如果想让解码错误提示更友好,可以把原来Bundle扩展里的try?替换为正式的错误抛出,修改后的扩展代码如下:

extension Bundle {
    func decode<T: Codable>(file: String) throws -> T {
        guard let url = self.url(forResource: file, withExtension: nil) else {
            throw NSError(domain: "BundleDecode", code: -1, userInfo: [NSLocalizedDescriptionKey: "无法在Bundle中找到文件:\(file)"])
        }
        let data = try Data(contentsOf: url)
        let decoder = JSONDecoder()
        return try decoder.decode(T.self, from: data)
    }
}

调用时增加do-catch即可处理异常场景:

do {
    let codes: [Codes] = try Bundle.main.decode(file: "codes.json")
} catch {
    print("解码失败:\(error.localizedDescription)")
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 12:15:04