Uploaded image for project: 'Swift'
  1. Swift
  2. SR-7788

Enum with String or Int RawRepresentable not encoded / decoded properly

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Open
    • Priority: Medium
    • Resolution: Unresolved
    • Component/s: Foundation
    • Labels:
      None

      Description

      description

      When using an enum value that is RawRepresentable with String or Int, the json encoded is an an array of alternating keys and values, Instead of a Dictionary.

       

      This bug is first discussed here : https://forums.swift.org/t/json-encoding-decoding-weird-encoding-of-dictionary-with-enum-values

      repro

      reproduced in Swift 4.1, (not tested in Swift 4.2)

      let json = "{\"key\": \"value\"}" 
      enum Key: String, Codable { 
         case key 
      } 
      let jsonData = Data(json.utf8)
      let dataToEncode = [Key.key: "value"]
      do { 
         let decoded = try JSONDecoder().decode([Key: String].self, from: jsonData)
         print(decoded)
         let encoded = try JSONEncoder().encode(dataToEncode)
         print(String(data: encoded, encoding: .utf8)!)
      } catch { 
         print(error) 
      }
      

      expected

      Encode and Decode a Dictionary with the enum value rawValue as the key.

      actual

      gives the following errors for the decoding part

      typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))
      

      give the following result for the encoding part

      [ "key", value ]
      

       

        Attachments

          Activity

            People

            • Assignee:
              itaiferber Itai Ferber
              Reporter:
              Zarghol Clément Nonn
            • Votes:
              11 Vote for this issue
              Watchers:
              12 Start watching this issue

              Dates

              • Created:
                Updated: