【问题标题】:Decode simple API array Swift解码简单的 API 数组 Swift
【发布时间】:2018-03-19 14:57:58
【问题描述】:

我正在努力解码 API 返回的特定对象,我无法找出正确的 struct

怎么了?

这里是返回的APIJSON

{
    "votes": [
     {
        "votesId": "1",
        "vote_nb": "6",
        "current_time": "0",
        "trend_up": "0",
        "trend_down": "0",
        "position_hold": "0",
        "position_buy": "0",
        "position_sell": "0"
    }]
}

我的代码是decodefetch

struct VoteData : Codable {
    let votes : [Votes]
}

struct Votes : Codable {
    let vote_nb : String
}

func fetchData(completion: @escaping (VoteData?, Error?) -> Void) {

    let url = URL(string: "...")!

    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
        guard let data = data else {
            completion(nil, error ?? APIError.unknownNetworkError)
            return
        }
        do {
            let result = try JSONDecoder().decode(VoteData.self, from: data); completion(result, nil)
            let vote_nb = result.votes.vote_nb // Value of type '[Votes]' has no member 'vote_nb'
            print("VOTE NUMBER: ", vote_nb)
        } catch let parseError {
            completion(nil, parseError)
        }
    }
    task.resume()
}

【问题讨论】:

  • 提示: result.votes 是一个数组,它可以有零个、一个或多个元素。
  • result.votes[0].vote_nb:D

标签: swift api struct decode


【解决方案1】:

首先选择数组的特定成员,然后检查该成员的属性。

改变这一行:

let vote_nb = result.votes.vote_nb

为此:

let vote_nb = result.votes[0].vote_nb

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多