【发布时间】: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"
}]
}
我的代码是decode 和fetch:
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