Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decodable conformance with property of enum type

I have this enum:

enum DealStatus:String {
    case PENDING = "Pending"
    case ACTIVE = "Active"
    case STOP = "Stop"
    case DECLINED = "Declined"
    case PAUSED = "Paused"
}

and struct:

struct ActiveDeals: Decodable {
    let keyword:            String
    let bookingType:        String
    let expiryDate:         Int
    let createdAt:          Int?
    let shopLocation:       String?
    let dealImages:         [DealImages]?
    let dealStatus:         String?
    let startingDate:       Int?
}

In struct I am trying to assign enum as type for dealStatus like this:

struct ActiveDeals: Decodable {
        let keyword:            String
        let bookingType:        String
        let expiryDate:         Int
        let createdAt:          Int?
        let shopLocation:       String?
        let dealImages:         [DealImages]?
        let dealStatus:         DealStatus
        let startingDate:       Int?
    }

But I am getting some compiler error:

Type 'ActiveDeals' does not conform to protocol 'Decodable'

Protocol requires initializer 'init(from:)' with type 'Decodable' (Swift.Decodable)

Cannot automatically synthesize 'Decodable' because 'DealStatus' does not conform to 'Decodable'

like image 586
Sushil Sharma Avatar asked Feb 14 '18 09:02

Sushil Sharma


1 Answers

The problem is that Swift can automatically synthesize the methods needed for Decodable only if all the properties of a struct are also Decodable and your enum is not Decodable.

Having just had a go in a playground, it seems you can make your enum Decodable just by declaring that it is and Swift will automatically synthesize the methods for you. i.e.

enum DealStatus:String, Decodable  
//                      ^^^^^^^^^ This is all you need
{
    case PENDING = "Pending"
    case ACTIVE = "Active"
    case STOP = "Stop"
    case DECLINED = "Declined"
    case PAUSED = "Paused"
}
like image 134
JeremyP Avatar answered Oct 31 '22 01:10

JeremyP