【问题标题】:How to customize raw value in an enum如何在枚举中自定义原始值
【发布时间】:2019-08-29 12:36:44
【问题描述】:

我的 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 中的日期键不断变化,我需要动态键。我想在我的模型中的枚举中使用此方法:

var dates = getFormatedDates()

let firstForcast: FirstForcast
let secondForcast: SecondForcast

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

有什么想法吗?

【问题讨论】:

    标签: json swift enums codable


    【解决方案1】:

    如下创建相关类型,

    // 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)
    }
    

    【讨论】:

    • 是的.. 如果值动态变化,不要依赖键。这样做
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-11
    • 2013-10-02
    • 1970-01-01
    相关资源
    最近更新 更多