How to populate table view with custom object?









up vote
1
down vote

favorite












I have a struct that conforms to the Codable protocol. I make an URLSession request and receive an JSON response. I encode the response into my custom struct that looks something like this.



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]



I get a single object Weather. However, inside the object Weather I want to populate the validTime, i.e. 01/01/2018 12:00, with the corresponding name matching "temperature" and corresponding values, i.e. 10.5 C.



So the rows will look something like:



[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]


In my controller I have something like:



var testWeatherObject : [Weather] = 


I only want a single header at the top displaying a single location i.e. New York.



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


override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
return testWeatherObject[section].timeEvents.count



The above crashes my app. I'm not sure how to get the correct row counts.



override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
let cell = tableView.dequeueReusableCell(withIdentifier: "WeatherDataCell", for: indexPath)

return cell










share|improve this question























  • Didn't you forget to register cell in viewDidLoad?
    – Robert Dresler
    Nov 11 at 15:48










  • It's rare to see an up-voted question with four answers, none of which are accepted. More, you haven't indicated that anything helped. Care to offer some input?
    – dfd
    Nov 11 at 18:46










  • @dfd just had time to go through them. Already accepted an answer. Thanks
    – xxFlashxx
    Nov 11 at 19:41














up vote
1
down vote

favorite












I have a struct that conforms to the Codable protocol. I make an URLSession request and receive an JSON response. I encode the response into my custom struct that looks something like this.



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]



I get a single object Weather. However, inside the object Weather I want to populate the validTime, i.e. 01/01/2018 12:00, with the corresponding name matching "temperature" and corresponding values, i.e. 10.5 C.



So the rows will look something like:



[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]


In my controller I have something like:



var testWeatherObject : [Weather] = 


I only want a single header at the top displaying a single location i.e. New York.



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


override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
return testWeatherObject[section].timeEvents.count



The above crashes my app. I'm not sure how to get the correct row counts.



override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
let cell = tableView.dequeueReusableCell(withIdentifier: "WeatherDataCell", for: indexPath)

return cell










share|improve this question























  • Didn't you forget to register cell in viewDidLoad?
    – Robert Dresler
    Nov 11 at 15:48










  • It's rare to see an up-voted question with four answers, none of which are accepted. More, you haven't indicated that anything helped. Care to offer some input?
    – dfd
    Nov 11 at 18:46










  • @dfd just had time to go through them. Already accepted an answer. Thanks
    – xxFlashxx
    Nov 11 at 19:41












up vote
1
down vote

favorite









up vote
1
down vote

favorite











I have a struct that conforms to the Codable protocol. I make an URLSession request and receive an JSON response. I encode the response into my custom struct that looks something like this.



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]



I get a single object Weather. However, inside the object Weather I want to populate the validTime, i.e. 01/01/2018 12:00, with the corresponding name matching "temperature" and corresponding values, i.e. 10.5 C.



So the rows will look something like:



[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]


In my controller I have something like:



var testWeatherObject : [Weather] = 


I only want a single header at the top displaying a single location i.e. New York.



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


override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
return testWeatherObject[section].timeEvents.count



The above crashes my app. I'm not sure how to get the correct row counts.



override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
let cell = tableView.dequeueReusableCell(withIdentifier: "WeatherDataCell", for: indexPath)

return cell










share|improve this question















I have a struct that conforms to the Codable protocol. I make an URLSession request and receive an JSON response. I encode the response into my custom struct that looks something like this.



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]



I get a single object Weather. However, inside the object Weather I want to populate the validTime, i.e. 01/01/2018 12:00, with the corresponding name matching "temperature" and corresponding values, i.e. 10.5 C.



So the rows will look something like:



[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]


In my controller I have something like:



var testWeatherObject : [Weather] = 


I only want a single header at the top displaying a single location i.e. New York.



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


override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
return testWeatherObject[section].timeEvents.count



The above crashes my app. I'm not sure how to get the correct row counts.



override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
let cell = tableView.dequeueReusableCell(withIdentifier: "WeatherDataCell", for: indexPath)

return cell







swift uitableview codable






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 11 at 17:47









rmaddy

236k27307374




236k27307374










asked Nov 11 at 15:45









xxFlashxx

1168




1168











  • Didn't you forget to register cell in viewDidLoad?
    – Robert Dresler
    Nov 11 at 15:48










  • It's rare to see an up-voted question with four answers, none of which are accepted. More, you haven't indicated that anything helped. Care to offer some input?
    – dfd
    Nov 11 at 18:46










  • @dfd just had time to go through them. Already accepted an answer. Thanks
    – xxFlashxx
    Nov 11 at 19:41
















  • Didn't you forget to register cell in viewDidLoad?
    – Robert Dresler
    Nov 11 at 15:48










  • It's rare to see an up-voted question with four answers, none of which are accepted. More, you haven't indicated that anything helped. Care to offer some input?
    – dfd
    Nov 11 at 18:46










  • @dfd just had time to go through them. Already accepted an answer. Thanks
    – xxFlashxx
    Nov 11 at 19:41















Didn't you forget to register cell in viewDidLoad?
– Robert Dresler
Nov 11 at 15:48




Didn't you forget to register cell in viewDidLoad?
– Robert Dresler
Nov 11 at 15:48












It's rare to see an up-voted question with four answers, none of which are accepted. More, you haven't indicated that anything helped. Care to offer some input?
– dfd
Nov 11 at 18:46




It's rare to see an up-voted question with four answers, none of which are accepted. More, you haven't indicated that anything helped. Care to offer some input?
– dfd
Nov 11 at 18:46












@dfd just had time to go through them. Already accepted an answer. Thanks
– xxFlashxx
Nov 11 at 19:41




@dfd just had time to go through them. Already accepted an answer. Thanks
– xxFlashxx
Nov 11 at 19:41












5 Answers
5






active

oldest

votes

















up vote
0
down vote



accepted










You may access an empty array so



return testWeatherObject.first?.timeEvents.count ?? 0





share|improve this answer



























    up vote
    0
    down vote













    If you don't have sections you don't need to implement numberOfSections(in tableView: UITableView)



    If you're only working with a single Weather object why not change the definition of testWeatherObject to



    var testWeatherObject = [TimeEvents]


    and your numberOfRowsInSection would then become



    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
    return testWeatherObject.count






    share|improve this answer



























      up vote
      0
      down vote













      If you want to have just single section, you don't have to set this. Delete these lines of code:



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



      And now if you want to have single table view cell for each timeEvent you should create your weather object



      var testWeatherObject = // your Weather object


      and in data source method numberOfRowInSection just say I want as many cells as testWeatherObject has timeEvents



      override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
      return testWeatherObject.timeEvents.count



      However I recommend not to use your Weather object as variable. Instead you should create array of TimeEvents



      var timeEvents = [/* your TimeEvents objects*/]


      and in table view data source method use just this



      override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
      return timeEvents.count






      share|improve this answer





























        up vote
        0
        down vote













        It’s crashing because you’re trying to access a nested array that is empty.



        I would check to see if testWeatherObjects.count is 0 first. If not then you can go ahead and use testWeatherObject[section].timeEvents.count






        share|improve this answer



























          up vote
          0
          down vote













          Does the identifier of cell defined in storyboard or xib match "WeatherDataCell"?



          I made a simple tableview app sample.
          https://github.com/y-okudera/TableViewDemoApp



          I hope to be helpful.






          share|improve this answer




















            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',
            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%2f53250388%2fhow-to-populate-table-view-with-custom-object%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            5 Answers
            5






            active

            oldest

            votes








            5 Answers
            5






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            0
            down vote



            accepted










            You may access an empty array so



            return testWeatherObject.first?.timeEvents.count ?? 0





            share|improve this answer
























              up vote
              0
              down vote



              accepted










              You may access an empty array so



              return testWeatherObject.first?.timeEvents.count ?? 0





              share|improve this answer






















                up vote
                0
                down vote



                accepted







                up vote
                0
                down vote



                accepted






                You may access an empty array so



                return testWeatherObject.first?.timeEvents.count ?? 0





                share|improve this answer












                You may access an empty array so



                return testWeatherObject.first?.timeEvents.count ?? 0






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 11 at 15:50









                Sh_Khan

                36.3k51125




                36.3k51125






















                    up vote
                    0
                    down vote













                    If you don't have sections you don't need to implement numberOfSections(in tableView: UITableView)



                    If you're only working with a single Weather object why not change the definition of testWeatherObject to



                    var testWeatherObject = [TimeEvents]


                    and your numberOfRowsInSection would then become



                    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
                    return testWeatherObject.count






                    share|improve this answer
























                      up vote
                      0
                      down vote













                      If you don't have sections you don't need to implement numberOfSections(in tableView: UITableView)



                      If you're only working with a single Weather object why not change the definition of testWeatherObject to



                      var testWeatherObject = [TimeEvents]


                      and your numberOfRowsInSection would then become



                      override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
                      return testWeatherObject.count






                      share|improve this answer






















                        up vote
                        0
                        down vote










                        up vote
                        0
                        down vote









                        If you don't have sections you don't need to implement numberOfSections(in tableView: UITableView)



                        If you're only working with a single Weather object why not change the definition of testWeatherObject to



                        var testWeatherObject = [TimeEvents]


                        and your numberOfRowsInSection would then become



                        override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
                        return testWeatherObject.count






                        share|improve this answer












                        If you don't have sections you don't need to implement numberOfSections(in tableView: UITableView)



                        If you're only working with a single Weather object why not change the definition of testWeatherObject to



                        var testWeatherObject = [TimeEvents]


                        and your numberOfRowsInSection would then become



                        override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
                        return testWeatherObject.count







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Nov 11 at 15:58









                        Joakim Danielson

                        6,0293621




                        6,0293621




















                            up vote
                            0
                            down vote













                            If you want to have just single section, you don't have to set this. Delete these lines of code:



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



                            And now if you want to have single table view cell for each timeEvent you should create your weather object



                            var testWeatherObject = // your Weather object


                            and in data source method numberOfRowInSection just say I want as many cells as testWeatherObject has timeEvents



                            override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
                            return testWeatherObject.timeEvents.count



                            However I recommend not to use your Weather object as variable. Instead you should create array of TimeEvents



                            var timeEvents = [/* your TimeEvents objects*/]


                            and in table view data source method use just this



                            override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
                            return timeEvents.count






                            share|improve this answer


























                              up vote
                              0
                              down vote













                              If you want to have just single section, you don't have to set this. Delete these lines of code:



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



                              And now if you want to have single table view cell for each timeEvent you should create your weather object



                              var testWeatherObject = // your Weather object


                              and in data source method numberOfRowInSection just say I want as many cells as testWeatherObject has timeEvents



                              override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
                              return testWeatherObject.timeEvents.count



                              However I recommend not to use your Weather object as variable. Instead you should create array of TimeEvents



                              var timeEvents = [/* your TimeEvents objects*/]


                              and in table view data source method use just this



                              override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
                              return timeEvents.count






                              share|improve this answer
























                                up vote
                                0
                                down vote










                                up vote
                                0
                                down vote









                                If you want to have just single section, you don't have to set this. Delete these lines of code:



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



                                And now if you want to have single table view cell for each timeEvent you should create your weather object



                                var testWeatherObject = // your Weather object


                                and in data source method numberOfRowInSection just say I want as many cells as testWeatherObject has timeEvents



                                override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
                                return testWeatherObject.timeEvents.count



                                However I recommend not to use your Weather object as variable. Instead you should create array of TimeEvents



                                var timeEvents = [/* your TimeEvents objects*/]


                                and in table view data source method use just this



                                override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
                                return timeEvents.count






                                share|improve this answer














                                If you want to have just single section, you don't have to set this. Delete these lines of code:



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



                                And now if you want to have single table view cell for each timeEvent you should create your weather object



                                var testWeatherObject = // your Weather object


                                and in data source method numberOfRowInSection just say I want as many cells as testWeatherObject has timeEvents



                                override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
                                return testWeatherObject.timeEvents.count



                                However I recommend not to use your Weather object as variable. Instead you should create array of TimeEvents



                                var timeEvents = [/* your TimeEvents objects*/]


                                and in table view data source method use just this



                                override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
                                return timeEvents.count







                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Nov 11 at 16:01

























                                answered Nov 11 at 15:55









                                Robert Dresler

                                1,666318




                                1,666318




















                                    up vote
                                    0
                                    down vote













                                    It’s crashing because you’re trying to access a nested array that is empty.



                                    I would check to see if testWeatherObjects.count is 0 first. If not then you can go ahead and use testWeatherObject[section].timeEvents.count






                                    share|improve this answer
























                                      up vote
                                      0
                                      down vote













                                      It’s crashing because you’re trying to access a nested array that is empty.



                                      I would check to see if testWeatherObjects.count is 0 first. If not then you can go ahead and use testWeatherObject[section].timeEvents.count






                                      share|improve this answer






















                                        up vote
                                        0
                                        down vote










                                        up vote
                                        0
                                        down vote









                                        It’s crashing because you’re trying to access a nested array that is empty.



                                        I would check to see if testWeatherObjects.count is 0 first. If not then you can go ahead and use testWeatherObject[section].timeEvents.count






                                        share|improve this answer












                                        It’s crashing because you’re trying to access a nested array that is empty.



                                        I would check to see if testWeatherObjects.count is 0 first. If not then you can go ahead and use testWeatherObject[section].timeEvents.count







                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Nov 11 at 16:05









                                        Philzeey

                                        143




                                        143




















                                            up vote
                                            0
                                            down vote













                                            Does the identifier of cell defined in storyboard or xib match "WeatherDataCell"?



                                            I made a simple tableview app sample.
                                            https://github.com/y-okudera/TableViewDemoApp



                                            I hope to be helpful.






                                            share|improve this answer
























                                              up vote
                                              0
                                              down vote













                                              Does the identifier of cell defined in storyboard or xib match "WeatherDataCell"?



                                              I made a simple tableview app sample.
                                              https://github.com/y-okudera/TableViewDemoApp



                                              I hope to be helpful.






                                              share|improve this answer






















                                                up vote
                                                0
                                                down vote










                                                up vote
                                                0
                                                down vote









                                                Does the identifier of cell defined in storyboard or xib match "WeatherDataCell"?



                                                I made a simple tableview app sample.
                                                https://github.com/y-okudera/TableViewDemoApp



                                                I hope to be helpful.






                                                share|improve this answer












                                                Does the identifier of cell defined in storyboard or xib match "WeatherDataCell"?



                                                I made a simple tableview app sample.
                                                https://github.com/y-okudera/TableViewDemoApp



                                                I hope to be helpful.







                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Nov 11 at 18:50









                                                yuoku

                                                361




                                                361



























                                                    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.





                                                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                                    Please pay close attention to the following guidance:


                                                    • 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%2f53250388%2fhow-to-populate-table-view-with-custom-object%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







                                                    Popular posts from this blog

                                                    27

                                                    Top Tejano songwriter Luis Silva dead of heart attack at 64

                                                    Category:Rhetoric