I have parsed a JSON file and now I am trying to create a table view with a section. The section is a dictionary inside the data model.
import Foundation
struct ActionResult: Codable {
let data: [ActionElement]
}
struct ActionElement: Codable {
let actionID: Int
let actionItem: String
let actionGoal: ActionGoal
let actionImage: String
let actionBenefit: ActionBenefit
let actionSavings: Int
let actionType: ActionType
let actionDescription, actionTips: String
let actionInformationURL: String
let actionSponsorURL: String
enum CodingKeys: String, CodingKey {
case actionID = "ActionID"
case actionItem = "ActionItem"
case actionGoal = "ActionGoal"
case actionImage = "ActionImage"
case actionBenefit = "ActionBenefit"
case actionSavings = "ActionSavings"
case actionType = "ActionType"
case actionDescription = "ActionDescription"
case actionTips = "ActionTips"
case actionInformationURL = "ActionInformationURL"
case actionSponsorURL = "ActionSponsorURL"
}
}
enum ActionBenefit: String, Codable {
case costs = "Costs"
case education = "Education"
case environment = "Environment"
case health = "Health"
}
enum ActionGoal: String, Codable {
case cleanEnergy = "Clean Energy"
case cleanWater = "Clean Water"
case climateAction = "Climate Action"
case economicGrowth = "Economic Growth"
case goodHealth = "Good Health"
case noPoverty = "No Poverty"
case promoteEquality = "Promote Equality"
case qualityEducation = "Quality Education"
case responsibleConsumption = "Responsible Consumption"
case zeroHunger = "Zero Hunger"
}
enum ActionType: String, Codable {
case sticky = "Sticky"
case todoe = "Todoe"
}
typealias Action = [ActionElement]
Now I am trying to create my table view section but I am getting the following error: Value of type '[ActionElement]' has no member 'actionGoal'
Two questions: How do I fix this? What is a good resource to understand more about data models and table views?
This is the code I am writing:
var result: ActionResult?
var index = 0
override func viewDidLoad() {
super.viewDidLoad()
parseJSON()
}
// Table View Sections
override func numberOfSections(in tableView: UITableView) -> Int {
return result?.data.count ?? 0
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return result?.data.actionGoal
}
CodePudding user response:
You forgot to access the array element
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return result?.data[section].actionGoal.rawValue
}
CodePudding user response:
I believe you need to index the data and then use the raw value (string) as ActionGoal
is an enum.
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return result?.data[section].actionGoal.rawValue
}