My First App – Week 3

Time to take a moment to recap week three in coding my first app.  Unfortunately, I did not make much time for coding this week so this update will be light.  That being said, let’s get started.

What I Learned

  • I need to look for more opportunities to use structs and classes
  • UI/ UX Design is not as easy as I thought (or I’m not as good at it as I thought I would be)

After last week, the app took another step forward in terms of actually being useful.  Now when you tap on a restaurant, the Nutritionix API will return up to fifty food results in a new table view.  I was able to accomplish that by building a custom-formatted URL that passes the unique restaurant ID to the API to return the desired results.  The API returns a JSON response and that is all decoded into something useable in Swift.

Refactoring Crappy Code

Initially when I was decoding the JSON response from Nutritionix, I was storing the results in a dictionary of dictionaries.  The primary dictionary key was the unique foodID, and the value was another dictionary of keys which described the foods nutrition information.

At the time, my logic was that I needed a way to be able to reference the foodID and be able to pull all of its associated nutrition information.  I quickly realized that this was going to lead me to some really crappy code.

  1. The first problem I discovered using a dictionary of dictionaries is that I wouldn’t be able to set explicit types.  Instead I had to have a dictionary of type String : [String : Any].  The Any was going to bite me later when I would have to convert this for every value each time I wanted to use it.
  2. The second issue was that I would need to “inception” into the dictionary, make sure I typed the key correctly, and then store the value as a unique variable.  This would work, but it would be a lot of unnecessary extra work and coding.

Struct FoodItem { }

After that realization, I decided to build a new data model in the form of a struct.  The struct gives me greater control and ease of access to the properties as I need them.  I can now build an array of FoodItems with all of the results from the restaurant.  Once I have the array, I will be able to use the index to to pull out the value of each property that I want to access.

This makes so much more sense once I put it into practice, and is obviously the better approach.  This is a valuable lesson for me to keep in mind as I continue programming.  Going forward, I will try to be more mindful of every opportunity to refactor my code into a reusable struct/ class/ function.

Next Up

  • Still need to work on building in some actual error handling
  • Need to come up with a good way of dealing with handling optional values
  • Need to find some “good design” inspiration for the UI/ UX