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

Decode fail with an optional enum property

    XMLWordPrintable

    Details

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

      Description

      Swift Codable is an awesome feature that i'm using very regularly. But while working with it I found an issue.

      So I have a basic struct like this:

      enum Children: String, Codable {
        case son
      }
      
      struct Parent: Codable {
        let children: Children?
      }
      

      And i tried to parse `Parent` with an undefined value from `Children`, i.e:

      let rawData = """
      {
        "children": "daughter"
      }
      """.data(using: .utf8)!
      
      try JSONDecoder().decode(Parent.self, from: rawData)
      

      The issue is instead of receving a Parent instance with `childrean = nil`, it through me a serialization error: 

      ▿ DecodingError
        ▿ dataCorrupted : Context
          ▿ codingPath : 1 element
            - 0 : CodingKeys(stringValue: "children", intValue: nil)
          - debugDescription : "Cannot initialize Children from invalid String value daughter"
          - underlyingError : nil
      

      Please refer to the playground file i attached below. Note that it will work if i define my own decode init function. (can just uncomment

       public init(from decoder: Decoder) throws 

      function in the playground)

       

      Thanks!

       

       

       

       

       

        Attachments

          Activity

            People

            • Assignee:
              Unassigned
              Reporter:
              thanhturin Ta Phuc Thanh
            • Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

              Dates

              • Created:
                Updated: