Swift 4 Decodable - Dictionary with enum as key

前端 未结 3 2085
我在风中等你
我在风中等你 2020-12-01 06:27

My data structure has an enum as a key, I would expect the below to decode automatically. Is this a bug or some configuration issue?

import Foundation

enum          


        
3条回答
  •  借酒劲吻你
    2020-12-01 07:11

    Following from Imanou's answer, and going super generic. This will convert any RawRepresentable enum keyed dictionary. No further code required in the Decodable items.

    public extension KeyedDecodingContainer
    {
        func decode(_ type: [K:V].Type, forKey key: Key) throws -> [K:V]
            where K: RawRepresentable, K: Decodable, K.RawValue == R,
                  V: Decodable,
                  R: Decodable, R: Hashable
        {
            let rawDictionary = try self.decode([R: V].self, forKey: key)
            var dictionary = [K: V]()
    
            for (key, value) in rawDictionary {
                guard let enumKey = K(rawValue: key) else {
                    throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: codingPath,
                         debugDescription: "Could not parse json key \(key) to a \(K.self) enum"))
                }
                
                dictionary[enumKey] = value
            }
    
            return dictionary
        }
    }
    

提交回复
热议问题