[英]Nested struct for UITableView Swift/JSON
我需要在 UITableView 中顯示主題和描述。
struct Topics: Decodable {
let subtopics: [subTopic]
struct subTopic: Decodable {
var topic = ""
var description = ""
}
}
TableView 的數據是通過 URL 發布請求獲取的,並在do/try/catch
塊內分配。
let Topics = Topics()
摘自 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
}
樣品 JSON:
{"subtopics":[{"topic":"Computer Science", "description":"beginner course"},{"topic":"Data Analysis", "description":"beginner course"}]}
您為變量賦予與結構相同的名稱。
let Topics = Topics()
不要那樣做。 它令人困惑,並可能導致意外行為。 命名約定將變量命名為小寫和結構/類大寫是有原因的。
為了減少混淆,頂部的 object 名稱不同,例如
struct Response: Decodable {
let subtopics: [SubTopic]
struct SubTopic: Decodable {
let topic, description : String
}
}
SubTopic
中的默認值(和var
)沒有意義。
我的下一個建議是省略頂部的 object 並聲明數據源數組
var subTopics = [Response.SubTopic]()
並分配
let response = try JSONDecoder().decode(Response.self, from: data)
self.subTopics = response.subtopics
這將清理表格視圖代碼並擺脫丑陋的選項
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.