How do I make an enum decodable in Swift?


In Swift, you can use the Codable protocol to make an enum decodable as well. In Swift, the Codable protocol is a very powerful concept to provide flexibility to decode and encode any type of value. Also, you can make an enum decodable as well. You have to just define an enum in your custom type. In order to make an enum decodable, the enum must conform to the Codable protocol. In this article, we will learn how to use the Codable protocol to make an enum decodable in Swift

What is the JSONDecoder Class?

The JSONDecoder class is then used to parse the JSON data from the file into an instance of the given Type either a class or structure. The decode(_:from:) method is used to deserialize the JSON data, and the resulting Type object is then returned to access the properties of the Type object.

We are attempting to read the same JSON given above as an example using the Codable protocol. Before we are ready to decode the JSON data using the JSONDecoder() class, let's prepare the model class to be provided at the time of decoding.

The following steps will be followed in this example.

Step 1 - Make a Sample JSON

In this step, we will create a sample JSON and save this as a ".json" file in your Xcode project. Here is the JSON that we will use in this example −

[
   {
      "title": "1904",
      "artist": "The Tallest Man on Earth",
      "year": "2012",
      "type": "hindi"
   },
   {
      "title": "#40",
      "artist": "Dave Matthews",
      "year": "1999",
      "type": "english"
   },
   {
      "title": "40oz to Freedom",
      "artist": "Sublime",
      "year": "1996",
      "type": "english"
   },
   {
      "title": "#41",
      "artist": "Dave Matthews",
      "year": "1996",
      "type": "punjabi"
   }
]

We saved this JSON file by naming it "sample.json" in the project directory. In the above json file, we create an array of dictionary objects.

Step 2 - Design a Struct

In this step, we will create a struct with the name "Song" along with properties to store the information of an object. Make sure, the enum must conform to the Codable protocol in order to make the enum decodable.

Example

struct Song: Codable {
   public enum SongType: String, Codable {
      case hindi = "hindi"
      case english = "english"
      case punjabi = "punjabi"
      case tamil = "tamil"
      case none = "none"
   }
   let title: String
   let artist: String
   let year: String
   let type: SongType?
}

In the above example, create a struct named “Song” with the properties. You can see the Song type has conformed to the Codable protocol. Also, define an enumeration named “SongType” with the different possible cases. You should notice that the SongType enum has also conformed to the Codable protocol in order to make it decodable.

Step 3 - Parse the JSON Data

In this step, we will do parsing the JSON file from the local directory and save it to the array of Song type. You can read the local JSON file from the main bundle and get convert it to the Data form. Here is the example code −

import UIKit
class CodableController: UIViewController {

   override func viewDidLoad() {
      super.viewDidLoad()
      decodeJSON()
   }
   func decodeJSON() {
   do {
         
         // creating path from the main bundle and getting data object from the path
         if let bundlePath = Bundle.main.path(forResource: "sample", ofType: "json"),
         let jsonData = try String(contentsOfFile: bundlePath).data(using: .utf8) {
          
            // decoding an array of songs
            let songs = try JSONDecoder().decode([Song].self, from: jsonData)
             
            // printing the type of song
            songs.forEach { 
               song in print("Song type: \(song.type?.rawValue ?? "")")
            }
         }
      } catch {
         print(error)
      }
   }
}

In the above example, we create a view controller named "CodableController" along with a method. In this method, we are reading the local JSON file from the main bundle. After that, we decode the JSON data using the JSONDecoder().decode() method. We passed the type "[Song].self" to the decode method, which returns an array of song objects if it is successfully decoded.

Output

Song type: hindi
Song type: english
Song type: english
Song type: punjabi

Conclusion

Swift provides the JSONDecoder class to encode and decode the JSON objects into Swift's model objects and vice versa. It's our responsibility to handle property declarations carefully, otherwise, it will cause you to generate errors.

In order to make enums decodable in Swift, you have to conform the Codable protocol to the enums as well. Without conforming to the codable protocol, you will get a compile-time error.

Updated on: 04-Apr-2023

873 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements