简体   繁体   English

UITableView Swift/JSON 的嵌套结构

[英]Nested struct for UITableView Swift/JSON

I need to display topic and description in a UITableView.我需要在 UITableView 中显示主题和描述。

struct Topics: Decodable {

let subtopics: [subTopic]

    struct subTopic: Decodable {
     
      var topic = ""
      var description = ""

    }
}

The data for the TableView is fetched with a URL post request and assigned inside a do/try/catch block. TableView 的数据是通过 URL 发布请求获取的,并在do/try/catch块内分配。

let Topics = Topics()

excerpt from URLRequest:摘自 URLRequest:

 self.Topics =  try JSONDecoder().decode(Topics.self, from: data)                  
 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "topicCell") as! topicCell

var subTopic = Topics?.subtopics[indexPath.row]

cell.topicLabel?.text = subTopic.topic
cell.descriptionTextView?.text = subTopic.description


return cell 
}


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

  return Topics?.subtopics.count
}

Sample JSON:样品 JSON:

{"subtopics":[{"topic":"Computer Science", "description":"beginner course"},{"topic":"Data Analysis", "description":"beginner course"}]}

You give the the variable the same name as the struct.您为变量赋予与结构相同的名称。

let Topics = Topics()

Don't do that.不要那样做。 It is confusing and can cause unexpected behavior.它令人困惑,并可能导致意外行为。 There is a reason for the naming convention to name variables lowercase and structs/classes uppercase.命名约定将变量命名为小写和结构/类大写是有原因的。

For less confusion name the top object different for example为了减少混淆,顶部的 object 名称不同,例如

struct Response: Decodable {
    
    let subtopics: [SubTopic]
    
    struct SubTopic: Decodable {
        
        let topic, description : String
        
    }
}

The default values (and var iables) in SubTopic make no sense. SubTopic中的默认值(和var )没有意义。

My next recommendation is to omit the top object and declare the data source array我的下一个建议是省略顶部的 object 并声明数据源数组

var subTopics = [Response.SubTopic]()

and assign并分配

let response = try JSONDecoder().decode(Response.self, from: data)
self.subTopics = response.subtopics

This will clean up the table view code and gets rid of the ugly optionals这将清理表格视图代码并摆脱丑陋的选项

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
    let cell = tableView.dequeueReusableCell(withIdentifier: "topicCell") as! topicCell

    let subTopic = subTopics[indexPath.row]
    cell.topicLabel?.text = subTopic.topic
    cell.descriptionTextView?.text = subTopic.description

    return cell 
}


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return subTopics.count
}

   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM