Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SR-10078] Decode fail with an optional enum property #52480

swift-ci opened this issue Mar 11, 2019 · 2 comments

[SR-10078] Decode fail with an optional enum property #52480

swift-ci opened this issue Mar 11, 2019 · 2 comments


Copy link

@swift-ci swift-ci commented Mar 11, 2019

Previous ID SR-10078
Radar None
Original Reporter thanhturin (JIRA User)
Type Bug

Attachment: Download

Additional Detail from JIRA
Votes 0
Component/s Compiler
Labels Bug, Codable
Assignee None
Priority Medium

md5: 9892ca2b5bd246ad11addcb4eddc868e

Issue 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:

DecodingErrordataCorrupted : ContextcodingPath : 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 {code:java} public init(from decoder: Decoder) throws

Copy link

@belkadan belkadan commented Mar 14, 2019

This is correct behavior. It may not be correct to just produce nil here—what if it's "list of users forbidden from accessing my secret data"? Providing custom decoding behavior via init(coder:) is the right way to communicate that to the compiler.

I'm leaving this open because it's a reasonable feature request for some kind of annotation on the property to treat unknown values as nil.

Copy link
Collaborator Author

@swift-ci swift-ci commented Mar 15, 2019

Comment by Ta Phuc Thanh (JIRA)

I got it. Thanks @belkadan for your answer!

@swift-ci swift-ci transferred this issue from apple/swift-issues Apr 25, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
None yet

No branches or pull requests

2 participants