Implement a TableView with Sections and populating it with data from a struct










0















I'm mostly new to iOS and Xcode dev, so I'm just here asking for some handholding for now...



I'm making an app with a TableView of medical symptoms. I've managed to populate the tableview with data from an array and separate that into sections depending medical specialty. However, I've run into a brick wall with regards to being able to checkmark multiple symptoms in the table, and save that for later use in another ViewController.



The easiest method for me to understand is to create a dictionary with the whole list of symptoms, and then assign a boolean value to each of the symptoms depending on whether it is checked or unchecked. But I have no idea how to implement a struct that houses all the data, as well as being able to separate it into sections.



I'm also wondering whether it would be better to just keep all the data in an external file and allow the app to access the data.



I can add the code I've written so far if needed.



Help would be much appreciated!



Below is my current implementation of the data source



 let SymptomsSections = ["General", "Respiratory", "Cardiac", "Abdominal", "Neurological", "Psychiatrical"]

let SymptomsList =
[
["Dry mouth", "Malaise", "Asthenia"],
["Dyspnoea", "Wheezing"],
["Orthopnoea", "Angina"],
["Coffee ground vomiting", "Melaena"],
["Agnosia", "Apraxia"]
]


and the code to write it in tableView



override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?

return self.SymptomsSections[section]


override func numberOfSections(in tableView: UITableView) -> Int

return self.SymptomsSections.count


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

return SymptomsList[section].count


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

let cell = tableView.dequeueReusableCell(withIdentifier: "SymptomsCell", for: indexPath)

cell.textLabel?.text = SymptomsList[indexPath.section][indexPath.row]
return cell










share|improve this question
























  • do you need to save those data locally ? to show each time the apps start ? or create them each time you open the application ?

    – Mohmmad S
    Nov 14 '18 at 8:24











  • I want the data stored locally, and the list will remain constant, and show when the app starts

    – Jeremy Hao-Yang Choi
    Nov 14 '18 at 8:28











  • you know storing data locally is a big topic, i recommend you to first create each time user open the application then after you have the ability to do them by your self you can jump to the next step and store them.

    – Mohmmad S
    Nov 14 '18 at 8:29
















0















I'm mostly new to iOS and Xcode dev, so I'm just here asking for some handholding for now...



I'm making an app with a TableView of medical symptoms. I've managed to populate the tableview with data from an array and separate that into sections depending medical specialty. However, I've run into a brick wall with regards to being able to checkmark multiple symptoms in the table, and save that for later use in another ViewController.



The easiest method for me to understand is to create a dictionary with the whole list of symptoms, and then assign a boolean value to each of the symptoms depending on whether it is checked or unchecked. But I have no idea how to implement a struct that houses all the data, as well as being able to separate it into sections.



I'm also wondering whether it would be better to just keep all the data in an external file and allow the app to access the data.



I can add the code I've written so far if needed.



Help would be much appreciated!



Below is my current implementation of the data source



 let SymptomsSections = ["General", "Respiratory", "Cardiac", "Abdominal", "Neurological", "Psychiatrical"]

let SymptomsList =
[
["Dry mouth", "Malaise", "Asthenia"],
["Dyspnoea", "Wheezing"],
["Orthopnoea", "Angina"],
["Coffee ground vomiting", "Melaena"],
["Agnosia", "Apraxia"]
]


and the code to write it in tableView



override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?

return self.SymptomsSections[section]


override func numberOfSections(in tableView: UITableView) -> Int

return self.SymptomsSections.count


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

return SymptomsList[section].count


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

let cell = tableView.dequeueReusableCell(withIdentifier: "SymptomsCell", for: indexPath)

cell.textLabel?.text = SymptomsList[indexPath.section][indexPath.row]
return cell










share|improve this question
























  • do you need to save those data locally ? to show each time the apps start ? or create them each time you open the application ?

    – Mohmmad S
    Nov 14 '18 at 8:24











  • I want the data stored locally, and the list will remain constant, and show when the app starts

    – Jeremy Hao-Yang Choi
    Nov 14 '18 at 8:28











  • you know storing data locally is a big topic, i recommend you to first create each time user open the application then after you have the ability to do them by your self you can jump to the next step and store them.

    – Mohmmad S
    Nov 14 '18 at 8:29














0












0








0








I'm mostly new to iOS and Xcode dev, so I'm just here asking for some handholding for now...



I'm making an app with a TableView of medical symptoms. I've managed to populate the tableview with data from an array and separate that into sections depending medical specialty. However, I've run into a brick wall with regards to being able to checkmark multiple symptoms in the table, and save that for later use in another ViewController.



The easiest method for me to understand is to create a dictionary with the whole list of symptoms, and then assign a boolean value to each of the symptoms depending on whether it is checked or unchecked. But I have no idea how to implement a struct that houses all the data, as well as being able to separate it into sections.



I'm also wondering whether it would be better to just keep all the data in an external file and allow the app to access the data.



I can add the code I've written so far if needed.



Help would be much appreciated!



Below is my current implementation of the data source



 let SymptomsSections = ["General", "Respiratory", "Cardiac", "Abdominal", "Neurological", "Psychiatrical"]

let SymptomsList =
[
["Dry mouth", "Malaise", "Asthenia"],
["Dyspnoea", "Wheezing"],
["Orthopnoea", "Angina"],
["Coffee ground vomiting", "Melaena"],
["Agnosia", "Apraxia"]
]


and the code to write it in tableView



override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?

return self.SymptomsSections[section]


override func numberOfSections(in tableView: UITableView) -> Int

return self.SymptomsSections.count


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

return SymptomsList[section].count


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

let cell = tableView.dequeueReusableCell(withIdentifier: "SymptomsCell", for: indexPath)

cell.textLabel?.text = SymptomsList[indexPath.section][indexPath.row]
return cell










share|improve this question
















I'm mostly new to iOS and Xcode dev, so I'm just here asking for some handholding for now...



I'm making an app with a TableView of medical symptoms. I've managed to populate the tableview with data from an array and separate that into sections depending medical specialty. However, I've run into a brick wall with regards to being able to checkmark multiple symptoms in the table, and save that for later use in another ViewController.



The easiest method for me to understand is to create a dictionary with the whole list of symptoms, and then assign a boolean value to each of the symptoms depending on whether it is checked or unchecked. But I have no idea how to implement a struct that houses all the data, as well as being able to separate it into sections.



I'm also wondering whether it would be better to just keep all the data in an external file and allow the app to access the data.



I can add the code I've written so far if needed.



Help would be much appreciated!



Below is my current implementation of the data source



 let SymptomsSections = ["General", "Respiratory", "Cardiac", "Abdominal", "Neurological", "Psychiatrical"]

let SymptomsList =
[
["Dry mouth", "Malaise", "Asthenia"],
["Dyspnoea", "Wheezing"],
["Orthopnoea", "Angina"],
["Coffee ground vomiting", "Melaena"],
["Agnosia", "Apraxia"]
]


and the code to write it in tableView



override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?

return self.SymptomsSections[section]


override func numberOfSections(in tableView: UITableView) -> Int

return self.SymptomsSections.count


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

return SymptomsList[section].count


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

let cell = tableView.dequeueReusableCell(withIdentifier: "SymptomsCell", for: indexPath)

cell.textLabel?.text = SymptomsList[indexPath.section][indexPath.row]
return cell







arrays swift xcode struct tableview






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 '18 at 9:00







Jeremy Hao-Yang Choi

















asked Nov 14 '18 at 8:19









Jeremy Hao-Yang ChoiJeremy Hao-Yang Choi

174




174












  • do you need to save those data locally ? to show each time the apps start ? or create them each time you open the application ?

    – Mohmmad S
    Nov 14 '18 at 8:24











  • I want the data stored locally, and the list will remain constant, and show when the app starts

    – Jeremy Hao-Yang Choi
    Nov 14 '18 at 8:28











  • you know storing data locally is a big topic, i recommend you to first create each time user open the application then after you have the ability to do them by your self you can jump to the next step and store them.

    – Mohmmad S
    Nov 14 '18 at 8:29


















  • do you need to save those data locally ? to show each time the apps start ? or create them each time you open the application ?

    – Mohmmad S
    Nov 14 '18 at 8:24











  • I want the data stored locally, and the list will remain constant, and show when the app starts

    – Jeremy Hao-Yang Choi
    Nov 14 '18 at 8:28











  • you know storing data locally is a big topic, i recommend you to first create each time user open the application then after you have the ability to do them by your self you can jump to the next step and store them.

    – Mohmmad S
    Nov 14 '18 at 8:29

















do you need to save those data locally ? to show each time the apps start ? or create them each time you open the application ?

– Mohmmad S
Nov 14 '18 at 8:24





do you need to save those data locally ? to show each time the apps start ? or create them each time you open the application ?

– Mohmmad S
Nov 14 '18 at 8:24













I want the data stored locally, and the list will remain constant, and show when the app starts

– Jeremy Hao-Yang Choi
Nov 14 '18 at 8:28





I want the data stored locally, and the list will remain constant, and show when the app starts

– Jeremy Hao-Yang Choi
Nov 14 '18 at 8:28













you know storing data locally is a big topic, i recommend you to first create each time user open the application then after you have the ability to do them by your self you can jump to the next step and store them.

– Mohmmad S
Nov 14 '18 at 8:29






you know storing data locally is a big topic, i recommend you to first create each time user open the application then after you have the ability to do them by your self you can jump to the next step and store them.

– Mohmmad S
Nov 14 '18 at 8:29













1 Answer
1






active

oldest

votes


















2














Updated answer



I ran the code shared by OP and noticed that it was crashing. The main reason why it does so is because SymptomsSections & SymptomsList does not have same number of contents, thus resulting in the out of index range crash for the smaller array which in our case is SymptomsList. For workaround I have added the line SymptomsList.indices.contains(index) which basically checks whether any object exists at the given index before accessing it. This resolved our crash. Then I proceeded to update the dictionaries and the accessing method. Also attached is the output screen for your understanding.



Please go through the code



let SymptomsSections = ["General", "Respiratory", "Cardiac", "Abdominal", "Neurological", "Psychiatrical"]

let SymptomsList = [[["name":"Dry mouth", "checked" : true], ["name":"Malaise", "checked" : false], ["name":"Asthenia", "checked" : true]],
[["name":"Dyspnoea", "checked" : true], ["name":"Wheezing", "checked" : false]],
[["name":"Orthopnoea", "checked" : false], ["name":"Angina", "checked" : true]],
[["name":"Coffee ground vomiting", "checked" : true], ["name":"Melaena", "checked" : true]],
[["name":"Agnosia", "checked" : false], ["name":"Apraxia", "checked" : true]]]


func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?
return self.SymptomsSections[section]



func numberOfSections(in tableView: UITableView) -> Int
return self.SymptomsSections.count


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
if SymptomsList.indices.contains(section)
return SymptomsList[section].count
else
return 0



func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
let cell = tableView.dequeueReusableCell(withIdentifier: "SymptomsCell", for: indexPath)
if SymptomsList.indices.contains(indexPath.section)
cell.textLabel?.text = SymptomsList[indexPath.section][indexPath.row]["name"] as? String
if SymptomsList[indexPath.section][indexPath.row]["checked"] as! Bool
cell.accessoryType = UITableViewCellAccessoryType.checkmark
else
cell.accessoryType = UITableViewCellAccessoryType.none

else
cell.textLabel?.text = nil
cell.accessoryType = UITableViewCellAccessoryType.none


return cell



enter image description here



Original answer



Well, to show something you need to know that thing. Not sure how you are getting your data. But I can imagine your datasource for tableview looks something like this:



let symptoms = ["fever", "cold", "heart ache"]


You're correct when you said that the easiest way out would be using dictionary. Imagine having the updated data source being an array of dictionaries, like so:



let symptoms = [["name":"fever", "checked":true], ["name":"cold", "checked":true], ["name":"heart ache", "checked":false]]


While assigning the cell in cellForRow method. You can use something like below:



cell.titleLabel.text = symptoms[indexPath.row]["name"] 
if symptoms[indexPath.row]["checked"]
cell.accessoryType = UITableViewCellAccessoryType.checkmark
else
cell.accessoryType = UITableViewCellAccessoryType.none






share|improve this answer

























  • I've attached what my code looks like at the moment. I see how you created the array of dictionaries, but would I be able to implement that into a tableView with sections?

    – Jeremy Hao-Yang Choi
    Nov 14 '18 at 9:01






  • 1





    @JeremyHao-YangChoi Yes ofcourse why not! Given if your code works the way you intend it to. Then the way I see it, you just have to make minor changes in the code base you shared. First change, would be to update SymptomsList to hold dictionary. Second change, would be the line cell.textLabel?.text = SymptomsList[indexPath.section][indexPath.row] as to how you would access it.

    – iOSer
    Nov 14 '18 at 9:24







  • 1





    @JeremyHao-YangChoi I've updated the answer to resolve the problems face in your specific code. If this or any other answer helps you in achieving what you wanted to achieve please do remember to mark them as correct, so that it helps others in future.

    – iOSer
    Nov 15 '18 at 9:38










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53295714%2fimplement-a-tableview-with-sections-and-populating-it-with-data-from-a-struct%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









2














Updated answer



I ran the code shared by OP and noticed that it was crashing. The main reason why it does so is because SymptomsSections & SymptomsList does not have same number of contents, thus resulting in the out of index range crash for the smaller array which in our case is SymptomsList. For workaround I have added the line SymptomsList.indices.contains(index) which basically checks whether any object exists at the given index before accessing it. This resolved our crash. Then I proceeded to update the dictionaries and the accessing method. Also attached is the output screen for your understanding.



Please go through the code



let SymptomsSections = ["General", "Respiratory", "Cardiac", "Abdominal", "Neurological", "Psychiatrical"]

let SymptomsList = [[["name":"Dry mouth", "checked" : true], ["name":"Malaise", "checked" : false], ["name":"Asthenia", "checked" : true]],
[["name":"Dyspnoea", "checked" : true], ["name":"Wheezing", "checked" : false]],
[["name":"Orthopnoea", "checked" : false], ["name":"Angina", "checked" : true]],
[["name":"Coffee ground vomiting", "checked" : true], ["name":"Melaena", "checked" : true]],
[["name":"Agnosia", "checked" : false], ["name":"Apraxia", "checked" : true]]]


func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?
return self.SymptomsSections[section]



func numberOfSections(in tableView: UITableView) -> Int
return self.SymptomsSections.count


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
if SymptomsList.indices.contains(section)
return SymptomsList[section].count
else
return 0



func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
let cell = tableView.dequeueReusableCell(withIdentifier: "SymptomsCell", for: indexPath)
if SymptomsList.indices.contains(indexPath.section)
cell.textLabel?.text = SymptomsList[indexPath.section][indexPath.row]["name"] as? String
if SymptomsList[indexPath.section][indexPath.row]["checked"] as! Bool
cell.accessoryType = UITableViewCellAccessoryType.checkmark
else
cell.accessoryType = UITableViewCellAccessoryType.none

else
cell.textLabel?.text = nil
cell.accessoryType = UITableViewCellAccessoryType.none


return cell



enter image description here



Original answer



Well, to show something you need to know that thing. Not sure how you are getting your data. But I can imagine your datasource for tableview looks something like this:



let symptoms = ["fever", "cold", "heart ache"]


You're correct when you said that the easiest way out would be using dictionary. Imagine having the updated data source being an array of dictionaries, like so:



let symptoms = [["name":"fever", "checked":true], ["name":"cold", "checked":true], ["name":"heart ache", "checked":false]]


While assigning the cell in cellForRow method. You can use something like below:



cell.titleLabel.text = symptoms[indexPath.row]["name"] 
if symptoms[indexPath.row]["checked"]
cell.accessoryType = UITableViewCellAccessoryType.checkmark
else
cell.accessoryType = UITableViewCellAccessoryType.none






share|improve this answer

























  • I've attached what my code looks like at the moment. I see how you created the array of dictionaries, but would I be able to implement that into a tableView with sections?

    – Jeremy Hao-Yang Choi
    Nov 14 '18 at 9:01






  • 1





    @JeremyHao-YangChoi Yes ofcourse why not! Given if your code works the way you intend it to. Then the way I see it, you just have to make minor changes in the code base you shared. First change, would be to update SymptomsList to hold dictionary. Second change, would be the line cell.textLabel?.text = SymptomsList[indexPath.section][indexPath.row] as to how you would access it.

    – iOSer
    Nov 14 '18 at 9:24







  • 1





    @JeremyHao-YangChoi I've updated the answer to resolve the problems face in your specific code. If this or any other answer helps you in achieving what you wanted to achieve please do remember to mark them as correct, so that it helps others in future.

    – iOSer
    Nov 15 '18 at 9:38















2














Updated answer



I ran the code shared by OP and noticed that it was crashing. The main reason why it does so is because SymptomsSections & SymptomsList does not have same number of contents, thus resulting in the out of index range crash for the smaller array which in our case is SymptomsList. For workaround I have added the line SymptomsList.indices.contains(index) which basically checks whether any object exists at the given index before accessing it. This resolved our crash. Then I proceeded to update the dictionaries and the accessing method. Also attached is the output screen for your understanding.



Please go through the code



let SymptomsSections = ["General", "Respiratory", "Cardiac", "Abdominal", "Neurological", "Psychiatrical"]

let SymptomsList = [[["name":"Dry mouth", "checked" : true], ["name":"Malaise", "checked" : false], ["name":"Asthenia", "checked" : true]],
[["name":"Dyspnoea", "checked" : true], ["name":"Wheezing", "checked" : false]],
[["name":"Orthopnoea", "checked" : false], ["name":"Angina", "checked" : true]],
[["name":"Coffee ground vomiting", "checked" : true], ["name":"Melaena", "checked" : true]],
[["name":"Agnosia", "checked" : false], ["name":"Apraxia", "checked" : true]]]


func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?
return self.SymptomsSections[section]



func numberOfSections(in tableView: UITableView) -> Int
return self.SymptomsSections.count


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
if SymptomsList.indices.contains(section)
return SymptomsList[section].count
else
return 0



func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
let cell = tableView.dequeueReusableCell(withIdentifier: "SymptomsCell", for: indexPath)
if SymptomsList.indices.contains(indexPath.section)
cell.textLabel?.text = SymptomsList[indexPath.section][indexPath.row]["name"] as? String
if SymptomsList[indexPath.section][indexPath.row]["checked"] as! Bool
cell.accessoryType = UITableViewCellAccessoryType.checkmark
else
cell.accessoryType = UITableViewCellAccessoryType.none

else
cell.textLabel?.text = nil
cell.accessoryType = UITableViewCellAccessoryType.none


return cell



enter image description here



Original answer



Well, to show something you need to know that thing. Not sure how you are getting your data. But I can imagine your datasource for tableview looks something like this:



let symptoms = ["fever", "cold", "heart ache"]


You're correct when you said that the easiest way out would be using dictionary. Imagine having the updated data source being an array of dictionaries, like so:



let symptoms = [["name":"fever", "checked":true], ["name":"cold", "checked":true], ["name":"heart ache", "checked":false]]


While assigning the cell in cellForRow method. You can use something like below:



cell.titleLabel.text = symptoms[indexPath.row]["name"] 
if symptoms[indexPath.row]["checked"]
cell.accessoryType = UITableViewCellAccessoryType.checkmark
else
cell.accessoryType = UITableViewCellAccessoryType.none






share|improve this answer

























  • I've attached what my code looks like at the moment. I see how you created the array of dictionaries, but would I be able to implement that into a tableView with sections?

    – Jeremy Hao-Yang Choi
    Nov 14 '18 at 9:01






  • 1





    @JeremyHao-YangChoi Yes ofcourse why not! Given if your code works the way you intend it to. Then the way I see it, you just have to make minor changes in the code base you shared. First change, would be to update SymptomsList to hold dictionary. Second change, would be the line cell.textLabel?.text = SymptomsList[indexPath.section][indexPath.row] as to how you would access it.

    – iOSer
    Nov 14 '18 at 9:24







  • 1





    @JeremyHao-YangChoi I've updated the answer to resolve the problems face in your specific code. If this or any other answer helps you in achieving what you wanted to achieve please do remember to mark them as correct, so that it helps others in future.

    – iOSer
    Nov 15 '18 at 9:38













2












2








2







Updated answer



I ran the code shared by OP and noticed that it was crashing. The main reason why it does so is because SymptomsSections & SymptomsList does not have same number of contents, thus resulting in the out of index range crash for the smaller array which in our case is SymptomsList. For workaround I have added the line SymptomsList.indices.contains(index) which basically checks whether any object exists at the given index before accessing it. This resolved our crash. Then I proceeded to update the dictionaries and the accessing method. Also attached is the output screen for your understanding.



Please go through the code



let SymptomsSections = ["General", "Respiratory", "Cardiac", "Abdominal", "Neurological", "Psychiatrical"]

let SymptomsList = [[["name":"Dry mouth", "checked" : true], ["name":"Malaise", "checked" : false], ["name":"Asthenia", "checked" : true]],
[["name":"Dyspnoea", "checked" : true], ["name":"Wheezing", "checked" : false]],
[["name":"Orthopnoea", "checked" : false], ["name":"Angina", "checked" : true]],
[["name":"Coffee ground vomiting", "checked" : true], ["name":"Melaena", "checked" : true]],
[["name":"Agnosia", "checked" : false], ["name":"Apraxia", "checked" : true]]]


func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?
return self.SymptomsSections[section]



func numberOfSections(in tableView: UITableView) -> Int
return self.SymptomsSections.count


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
if SymptomsList.indices.contains(section)
return SymptomsList[section].count
else
return 0



func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
let cell = tableView.dequeueReusableCell(withIdentifier: "SymptomsCell", for: indexPath)
if SymptomsList.indices.contains(indexPath.section)
cell.textLabel?.text = SymptomsList[indexPath.section][indexPath.row]["name"] as? String
if SymptomsList[indexPath.section][indexPath.row]["checked"] as! Bool
cell.accessoryType = UITableViewCellAccessoryType.checkmark
else
cell.accessoryType = UITableViewCellAccessoryType.none

else
cell.textLabel?.text = nil
cell.accessoryType = UITableViewCellAccessoryType.none


return cell



enter image description here



Original answer



Well, to show something you need to know that thing. Not sure how you are getting your data. But I can imagine your datasource for tableview looks something like this:



let symptoms = ["fever", "cold", "heart ache"]


You're correct when you said that the easiest way out would be using dictionary. Imagine having the updated data source being an array of dictionaries, like so:



let symptoms = [["name":"fever", "checked":true], ["name":"cold", "checked":true], ["name":"heart ache", "checked":false]]


While assigning the cell in cellForRow method. You can use something like below:



cell.titleLabel.text = symptoms[indexPath.row]["name"] 
if symptoms[indexPath.row]["checked"]
cell.accessoryType = UITableViewCellAccessoryType.checkmark
else
cell.accessoryType = UITableViewCellAccessoryType.none






share|improve this answer















Updated answer



I ran the code shared by OP and noticed that it was crashing. The main reason why it does so is because SymptomsSections & SymptomsList does not have same number of contents, thus resulting in the out of index range crash for the smaller array which in our case is SymptomsList. For workaround I have added the line SymptomsList.indices.contains(index) which basically checks whether any object exists at the given index before accessing it. This resolved our crash. Then I proceeded to update the dictionaries and the accessing method. Also attached is the output screen for your understanding.



Please go through the code



let SymptomsSections = ["General", "Respiratory", "Cardiac", "Abdominal", "Neurological", "Psychiatrical"]

let SymptomsList = [[["name":"Dry mouth", "checked" : true], ["name":"Malaise", "checked" : false], ["name":"Asthenia", "checked" : true]],
[["name":"Dyspnoea", "checked" : true], ["name":"Wheezing", "checked" : false]],
[["name":"Orthopnoea", "checked" : false], ["name":"Angina", "checked" : true]],
[["name":"Coffee ground vomiting", "checked" : true], ["name":"Melaena", "checked" : true]],
[["name":"Agnosia", "checked" : false], ["name":"Apraxia", "checked" : true]]]


func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?
return self.SymptomsSections[section]



func numberOfSections(in tableView: UITableView) -> Int
return self.SymptomsSections.count


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
if SymptomsList.indices.contains(section)
return SymptomsList[section].count
else
return 0



func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
let cell = tableView.dequeueReusableCell(withIdentifier: "SymptomsCell", for: indexPath)
if SymptomsList.indices.contains(indexPath.section)
cell.textLabel?.text = SymptomsList[indexPath.section][indexPath.row]["name"] as? String
if SymptomsList[indexPath.section][indexPath.row]["checked"] as! Bool
cell.accessoryType = UITableViewCellAccessoryType.checkmark
else
cell.accessoryType = UITableViewCellAccessoryType.none

else
cell.textLabel?.text = nil
cell.accessoryType = UITableViewCellAccessoryType.none


return cell



enter image description here



Original answer



Well, to show something you need to know that thing. Not sure how you are getting your data. But I can imagine your datasource for tableview looks something like this:



let symptoms = ["fever", "cold", "heart ache"]


You're correct when you said that the easiest way out would be using dictionary. Imagine having the updated data source being an array of dictionaries, like so:



let symptoms = [["name":"fever", "checked":true], ["name":"cold", "checked":true], ["name":"heart ache", "checked":false]]


While assigning the cell in cellForRow method. You can use something like below:



cell.titleLabel.text = symptoms[indexPath.row]["name"] 
if symptoms[indexPath.row]["checked"]
cell.accessoryType = UITableViewCellAccessoryType.checkmark
else
cell.accessoryType = UITableViewCellAccessoryType.none







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 14 '18 at 11:54

























answered Nov 14 '18 at 8:42









iOSeriOSer

836720




836720












  • I've attached what my code looks like at the moment. I see how you created the array of dictionaries, but would I be able to implement that into a tableView with sections?

    – Jeremy Hao-Yang Choi
    Nov 14 '18 at 9:01






  • 1





    @JeremyHao-YangChoi Yes ofcourse why not! Given if your code works the way you intend it to. Then the way I see it, you just have to make minor changes in the code base you shared. First change, would be to update SymptomsList to hold dictionary. Second change, would be the line cell.textLabel?.text = SymptomsList[indexPath.section][indexPath.row] as to how you would access it.

    – iOSer
    Nov 14 '18 at 9:24







  • 1





    @JeremyHao-YangChoi I've updated the answer to resolve the problems face in your specific code. If this or any other answer helps you in achieving what you wanted to achieve please do remember to mark them as correct, so that it helps others in future.

    – iOSer
    Nov 15 '18 at 9:38

















  • I've attached what my code looks like at the moment. I see how you created the array of dictionaries, but would I be able to implement that into a tableView with sections?

    – Jeremy Hao-Yang Choi
    Nov 14 '18 at 9:01






  • 1





    @JeremyHao-YangChoi Yes ofcourse why not! Given if your code works the way you intend it to. Then the way I see it, you just have to make minor changes in the code base you shared. First change, would be to update SymptomsList to hold dictionary. Second change, would be the line cell.textLabel?.text = SymptomsList[indexPath.section][indexPath.row] as to how you would access it.

    – iOSer
    Nov 14 '18 at 9:24







  • 1





    @JeremyHao-YangChoi I've updated the answer to resolve the problems face in your specific code. If this or any other answer helps you in achieving what you wanted to achieve please do remember to mark them as correct, so that it helps others in future.

    – iOSer
    Nov 15 '18 at 9:38
















I've attached what my code looks like at the moment. I see how you created the array of dictionaries, but would I be able to implement that into a tableView with sections?

– Jeremy Hao-Yang Choi
Nov 14 '18 at 9:01





I've attached what my code looks like at the moment. I see how you created the array of dictionaries, but would I be able to implement that into a tableView with sections?

– Jeremy Hao-Yang Choi
Nov 14 '18 at 9:01




1




1





@JeremyHao-YangChoi Yes ofcourse why not! Given if your code works the way you intend it to. Then the way I see it, you just have to make minor changes in the code base you shared. First change, would be to update SymptomsList to hold dictionary. Second change, would be the line cell.textLabel?.text = SymptomsList[indexPath.section][indexPath.row] as to how you would access it.

– iOSer
Nov 14 '18 at 9:24






@JeremyHao-YangChoi Yes ofcourse why not! Given if your code works the way you intend it to. Then the way I see it, you just have to make minor changes in the code base you shared. First change, would be to update SymptomsList to hold dictionary. Second change, would be the line cell.textLabel?.text = SymptomsList[indexPath.section][indexPath.row] as to how you would access it.

– iOSer
Nov 14 '18 at 9:24





1




1





@JeremyHao-YangChoi I've updated the answer to resolve the problems face in your specific code. If this or any other answer helps you in achieving what you wanted to achieve please do remember to mark them as correct, so that it helps others in future.

– iOSer
Nov 15 '18 at 9:38





@JeremyHao-YangChoi I've updated the answer to resolve the problems face in your specific code. If this or any other answer helps you in achieving what you wanted to achieve please do remember to mark them as correct, so that it helps others in future.

– iOSer
Nov 15 '18 at 9:38



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53295714%2fimplement-a-tableview-with-sections-and-populating-it-with-data-from-a-struct%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







這個網誌中的熱門文章

How to read a connectionString WITH PROVIDER in .NET Core?

In R, how to develop a multiplot heatmap.2 figure showing key labels successfully

Museum of Modern and Contemporary Art of Trento and Rovereto