You need to enable JavaScript to run this app. 如何用Swift Codable的PropertyListDecoder解析plist并保留字典排序
优惠活动
大模型
产品
解决方案
定价
更多

如何用Swift Codable的PropertyListDecoder解析plist并保留字典排序

核心原理

Swift 原生的 Dictionary 是无序哈希表结构,所以默认用 Codable 解析 plist 字典时会丢失原始顺序。PropertyListDecoder 本身会保留 plist 字典的键顺序,对应的 keyedContainer.allKeys 属性的排列顺序和 plist 中的条目顺序完全一致,我们只要按这个顺序读取键值对即可实现需求。

方案1:适配 OrderedDictionary 支持 Codable

如果你已经在使用 swift-collections 库的 OrderedDictionary,只需要扩展它实现 Decodable 协议即可:

import OrderedCollections

fileprivate struct GenericCodingKey: CodingKey {
    let stringValue: String
    let intValue: Int?
    
    init?(stringValue: String) {
        self.stringValue = stringValue
        self.intValue = nil
    }
    
    init?(intValue: Int) {
        self.intValue = intValue
        self.stringValue = "\(intValue)"
    }
}

extension OrderedDictionary: Decodable where Key == String, Value: Decodable {
    public init(from decoder: Decoder) throws {
        self.init()
        let container = try decoder.container(keyedBy: GenericCodingKey.self)
        for key in container.allKeys {
            let value = try container.decode(Value.self, forKey: key)
            self[key.stringValue] = value
        }
    }
}

使用时直接替换模型中的字典类型即可:

struct Model: Decodable {
    let container: OrderedDictionary<String, String> // 解析后完全保留plist原始顺序
}

方案2:解析为键值对数组(无第三方依赖)

如果不想引入外部库,可以直接将有序字典解析为存储键值对的元组数组:

fileprivate struct GenericCodingKey: CodingKey {
    let stringValue: String
    let intValue: Int?
    
    init?(stringValue: String) {
        self.stringValue = stringValue
        self.intValue = nil
    }
    
    init?(intValue: Int) {
        self.intValue = intValue
        self.stringValue = "\(intValue)"
    }
}

struct Model: Decodable {
    let container: [(key: String, value: String)]
    
    enum RootCodingKeys: String, CodingKey {
        case container
    }
    
    init(from decoder: Decoder) throws {
        let rootContainer = try decoder.container(keyedBy: RootCodingKeys.self)
        let dictContainer = try rootContainer.nestedContainer(keyedBy: GenericCodingKey.self, forKey: .container)
        var orderedItems = [(key: String, value: String)]()
        // 按plist原始顺序遍历读取
        for key in dictContainer.allKeys {
            let value = try dictContainer.decode(String.self, forKey: key)
            orderedItems.append((key.stringValue, value))
        }
        self.container = orderedItems
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 08:45:01