我有一个符合 Codable 协议(protocol)的结构。我发出 URLSession 请求并收到 JSON 响应。我将响应编码到我的自定义结构中,看起来像这样。
struct Weather: Codable {
let time: Date
let location: String
let timeEvents: [TimeEvents]
}
struct TimeEvents: Codable {
let validTime: Date
let parameters: [Parameters]
}
struct Parameters: Codable {
let name: String
let unit: String
let values: [Double]
}
我得到一个对象天气。但是,在对象 Weather 中,我想填充 validTime
,即 01/01/2018 12:00
,以及相应的 名称
匹配“温度”和相应的值
,即 10.5 C
。
所以行看起来像这样:
[01/01/2018 12:00 : 10.5C]
[01/01/2018 13:00 : 11.5C]
[01/01/2018 14:00 : 11.6C]
.
.
.
[02/01/2018 00:00 : 3.1C]
[02/01/2018 01:00 : 3.1C]
在我的 Controller 中我有类似的东西:
var testWeatherObject : [Weather] = []
我只想在顶部显示一个单独的标题,即纽约。
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return testWeatherObject[section].timeEvents.count
}
以上内容使我的应用程序崩溃。我不确定如何获得正确的行数。
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "WeatherDataCell", for: indexPath)
return cell
}
最佳答案
你可以这样访问一个空数组
return testWeatherObject.first?.timeEvents.count ?? 0
关于swift - 如何使用自定义对象填充 TableView ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53250388/