swiftlang / swift

The Swift Programming Language
https://swift.org
Apache License 2.0
67.6k stars 10.37k forks source link

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

Open swift-ci opened 5 years ago

swift-ci commented 5 years ago
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:

▿ 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

belkadan commented 5 years ago

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.

swift-ci commented 5 years ago

Comment by Ta Phuc Thanh (JIRA)

I got it. Thanks @belkadan for your answer!