【问题标题】:Is there any way to take a number as variable's name?有没有办法将数字作为变量的名称?
【发布时间】:2019-11-05 06:02:51
【问题描述】:

我有 JSON 响应,其中有“0”作为 JSON 的键值。我正在使用 Swift 的 Codable 协议来解析我的 JSON。有什么方法可以将“0”作为变量的名称或其他一些解决方法?我知道用于解析 JSON 的 SwiftyJSON,但我更喜欢使用本地 swift 协议。 This is my JSON response.

【问题讨论】:

    标签: json ios13 swift4.2


    【解决方案1】:

    如果“0”键是常量,您可以使用CodingKeys 将其映射到有效的属性名称,如下所示:

    struct Response: Codable {
        let success: Bool
        let data: DataClass
        let error, message: String
    }
    
    struct ZeroKeyType: Codable {
        // properties go here
    }
    
    struct DataClass: Codable {
        let the0: ZeroKeyType
        let searchField: [String]
    
        enum CodingKeys: String, CodingKey {
            case the0 = "0"
            case searchField
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-12-17
      • 2019-11-14
      • 2020-02-26
      • 2012-01-02
      • 2021-12-11
      • 2022-01-26
      • 1970-01-01
      • 2021-06-22
      • 1970-01-01
      相关资源
      最近更新 更多