首页 > 解决方案 > 如何在枚举中自定义原始值

问题描述

我的 json 是什么样的:

{
    "2019-08-27 19:00:00": {
        "temperature": {
            "sol":292
        }
    }
,
    "2019-08-28 19:00:00": {
        "temperature": {
            "sol":500
        }
    }
}

这是一种以所需格式获取当前未来五天的方法:

func getFormatedDates() -> [String] {

    let date = Date()
    let format = DateFormatter()
    format.dateFormat = "yyyy-MM-dd"

    var dateComponents = DateComponents()
    var dates = [String]()
    for i in 0...4 {
        dateComponents.setValue(i, for: .day)
        guard let nextDay = Calendar.current.date(byAdding: dateComponents, to: date) else { return [""] }
        let formattedDate = format.string(from: nextDay)
        dates.append(formattedDate + " " + "19:00:00")
    }
    return dates
}

由于 API 中的日期键不断变化,我需要动态键。我想在我的 Model 中的枚举中使用此方法:

var dates = getFormatedDates()

let firstForcast: FirstForcast
let secondForcast: SecondForcast

enum CodingKeys: String, CodingKey {
    case firstForcast = dates[0]
    case secondForcast = dates[1]
}

有任何想法吗 ?

标签: jsonswiftenumscodable

解决方案


创建如下相关类型,

// MARK: - PostBodyValue
struct PostBodyValue: Codable {
    let temperature: Temperature
}

// MARK: - Temperature
struct Temperature: Codable {
    let sol: Int
}

typealias PostBody = [String: PostBodyValue]

decode像这样,

do {
    let data = // Data from the API
    let objects = try JSONDecoder().decode(PostBody.self, from: data)
    for(key, value) in objects {
        print(key)
        print(value.temperature.sol)
    }
} catch {
    print(error)
}

推荐阅读