【问题标题】:Plist with different dictionaries to a struct具有不同字典的 Plist 到结构
【发布时间】:2018-11-14 05:50:53
【问题描述】:

我有一个plist,它是一个字典数组。 (根是数组)。 每个 dic 肯定有 2 个值:nameiconStrings。 但其中一些有更多的键/值,一些没有

我正在尝试将数组读入结构中:

struct Config: Decodable {
    private enum CodingKeys: String, CodingKey {
        case name, icon
    }

    let name: String
    let icon: String
}



func functionsStruct() -> Config {
    let url = Bundle.main.url(forResource: "FunctionsList", withExtension: "plist")!
    let data = try! Data(contentsOf: url)
    let decoder = PropertyListDecoder()
    return try! decoder.decode(Config.self, from: data)
}
  1. 我读了一本字典,如何读取字典数组以及如何设置结构。

  2. 如何解决某些 dic 有其他键没有的问题?

【问题讨论】:

  • 您可以将这些键设为可选。例如let someProperty: String?.
  • 谢谢,问题是如何保存字典数组而不是数组。想不通。
  • 解码[Config].self 不起作用?

标签: swift dictionary struct plist


【解决方案1】:

第一个问题:

我读了一本字典,如何读取字典数组以及如何设置结构。

func functionsStruct() -> [Config] {
            let url = Bundle.main.url(forResource: "FunctionsList", withExtension: "plist")!
            let data = try! Data(contentsOf: url)
            let decoder = PropertyListDecoder()
            return try! decoder.decode([Config].self, from: data)
        }

就这么简单!!!

【讨论】:

    【解决方案2】:

    如果你想要一个字典数组,那么你不需要创建自己的Codable 类。数组和字典已经实现了Codable

    只要做:

    func functionsStruct() -> [[String: String]] {
        let url = Bundle.main.url(forResource: "FunctionsList", withExtension: "plist")!
        let data = try! Data(contentsOf: url)
        let decoder = PropertyListDecoder()
        return try! decoder.decode([[String: String]].self, from: data)
    }
    

    如果字典包含字符串以外的值,则使用[[String: Any]]

    然后您可以像这样访问您的nameicon

    let dicts = functionsStruct()
    print(dicts[0]["name"])
    

    但是,我不明白您为什么坚持使用字典。我强烈建议您坚持使用 Codable 结构。您可以将可选键设为可选:

    struct Config: Decodable {
        let name: String
        let icon: String
        let optionalKey1: String?
        let optionalKey2: String?
    }
    

    如果 plist 中不存在键,则它们的值将为 nil。

    您需要解码Config 的数组,而不是像您那样只解码Config

    return try! decoder.decode([Config].self, from: data)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-15
      • 1970-01-01
      • 1970-01-01
      • 2023-01-11
      • 1970-01-01
      • 1970-01-01
      • 2019-08-18
      • 1970-01-01
      相关资源
      最近更新 更多