Adam Cooper
Adam Cooper

Reputation: 877

Decodable & Enum Values

How should I handle the situation where an enum value does not exist when decoding an object? For example, how would I handle the case where "horrible" is the rating type in the example below? Is there a way to set a default value if none of the values exist?

public struct Review: Decodable {

    public var ratingType: RatingType?

    enum CodingKeys: String, CodingKey {
        case ratingType = "rating_type"
    }

    public init(from decoder: Decoder) throws {

        let container = try decoder.container(keyedBy: CodingKeys.self)
        ratingType = try container.decodeIfPresent(RatingType.self, forKey: .ratingType)
    }
}

public enum RatingType: String, Codable {
    case Good = "good"
    case Bad = "bad"
}

Upvotes: 0

Views: 2181

Answers (2)

djromero
djromero

Reputation: 19641

In the case that the received unexpected rating should be actually used (defensive coding against a version mismatch between client and server or whatever) you can try with a different enum definition:

enum RatingType
{
    case good
    case bad
    case other(String)
}

You lose the automatic encoding but gain flexibility.

A possible implementation:

import Foundation

struct Review
{
    public var rating: RatingType?

    enum CodingKeys: String, CodingKey {
        case rating = "rating_type"
    }

    public init(rating: RatingType) {
        self.rating = rating
    }
}

extension Review: Decodable
{
    public init(from decoder: Decoder) throws {

        let container = try decoder.container(keyedBy: CodingKeys.self)
        if let label = try container.decodeIfPresent(String.self, forKey: .rating) {
            rating = RatingType(label: label)
        }
    }
}

extension Review: Encodable
{
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        if let rating = rating {
            try container.encode(rating.label, forKey: .rating)
        }
    }
}

.

enum RatingType
{
    case good
    case bad
    case other(String)

    init(label: String) {
        switch label {
            case "good": self = .good
            case "bad": self = .bad
            default: self = .other(label)
        }
    }

    var label: String {
        switch self {
            case .bad: return "bad"
            case .good: return "good"
            case let .other(label): return label
        }
    }
}

In real life you may want to make RatingType conforming to Codable/Decodable instead, simplifying the coding/encoding. Feel free to modify.

An example exercising the encoding/decoding:

func encode_review(_ review: Review) throws -> String
{
    let data = try JSONEncoder().encode(review)
    return String(data: data, encoding: String.Encoding.utf8) ?? "/* ERROR */"
}

func decode_json(_ json: String) throws -> Review?
{
    guard let data = json.data(using: String.Encoding.utf8) else { return nil }
    let review = try JSONDecoder().decode(Review.self, from: data)
    return review
}

print(try! encode_review(Review(rating: .good)))  // {"rating_type":"good"}
print(try! encode_review(Review(rating: .other("horrible")))) // {"rating_type":"horrible"}

let good_review_json = """
    {"rating_type":"good"}
"""
let great_review_json = """
    {"rating_type":"great"}
"""

if let review = try! decode_json(good_review_json), let label = review.rating?.label {
    print(label) // good
}
if let review = try! decode_json(great_review_json), let label = review.rating?.label {
    print(label) // great
}

Upvotes: 1

Sweeper
Sweeper

Reputation: 272000

decodeIfPresent returns nil if the key is not present, and it will likely throw an error if the value is invalid. By using try?, we can do this:

ratingType = 
    (try? (container.decodeIfPresent(RatingType.self, forKey: .ratingType) ?? <some default value>)
    ) ?? <some default value>

Upvotes: 2

Related Questions