swift - 如何使用自定义对象填充 TableView ?

标签 swift uitableview codable

我有一个符合 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/

相关文章:

ios - 如何在 UIStackView 中等距放置标签?

ios - Swift TableView 地址簿数组错误

ios - swift 4 可编码 : Common struct for all model

ios - 在 Swift 中使用 Switch 语句 - 值绑定(bind)在括号内还是在外?

ios - 在 iOS 9 上关闭 viewController 时的延迟

ios - 如何将帖子字符串写入API swift 3

swift - 在 Swift 4 中使用 Decodable 和继承

ios - 具有动态原型(prototype)内容和多部分的 UITableView

iphone - 图像并排在数组 xcode 中(在 UITableViewCell 中)

swift - 使用带有未知字典键的 Swift 4 Codable 协议(protocol)