CaseIterable in Action

Swift_logoIn my last post, I started off refactoring We Read Too into MVMM with RxSwift. In the “What’s Next” section I mentioned that I need to add another field to the suggestion form. So far, the suggestion form only has a two text fields, one for title and the other for author, and a button for submitting the form.

In the current version of the app, there is a third text field for the user to write in the genre of the book they are suggesting. Unfortunately having that third text field leads to a lot of book suggestions that are out of the scope of the app. We Read Too focuses on children’s and young adult books, so the third field should be a picker view instead of a text field so I can pre-populate the options for genre. This hopefully will lead to more relevant submissions.

In Swift 4.2, enums can now adhere to a CaseIterable protocol which allows us to easily get an array of all the enum cases and have access to the total count without having to implement that ourselves in a public variable on the enum. You can read the proposal for CaseIterable here.

The code snippet above shows my enum Category. Category will be used for the picker view in our suggestion and later as well when we populate the collection view of books which will be filtered by these particular categories. You may wonder why I just don’t make the cases equal to what’s in the description variable? Well we’re going to need the shorthand names (PB, CB, MG, YA) later for pulling the book data from Firebase.

Above is the enum in action, we use the just operator to create an Observable that emits the array of our all the cases that we can bind to the category picker view’s item titles. Then when any of the items are selected when can send it back to our view model and use the selected item to complete the suggestion form.

Simulator Screen Shot - iPhone X - 2018-06-26 at 22.26.50_iphonexspacegrey_portrait

What’s Next

Now that we’ve gotten our complete form, we can use this data to create a decodable Suggestion object and send it off to Firebase where we’re storing all the suggestions.

One thought on “CaseIterable in Action”

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s