Skip to content

[SR-10781] Decode an encoded double optional fails #3409

Open
@swift-ci

Description

@swift-ci
Previous ID SR-10781
Radar None
Original Reporter ChaosCoder (JIRA User)
Type Bug
Environment

Swift 5.0

Additional Detail from JIRA
Votes 0
Component/s Compiler, Foundation
Labels Bug, Codable
Assignee bendjones (JIRA)
Priority Medium

md5: 076bfab4f40c06914f7da38d175cf6d4

Issue Description:

I'm trying to encode and decode a Codable struct that has a double optional (e.g. name: String??).

This way, encoding the struct with the JSONEncoder, I get a json with:

  • the property and its value in it, if it is .some: { name: "123" }
  • nothing, if it is .none: {}
  • the property and null, if it is .some(.none): { name: null }

Trying to decode this json again does not handle the third case correctly, the decoded value is .none (like the second case):

import Foundation

struct S: Codable {
    let name: String??
}

let a = S(name: "123")
let jsonA = try! JSONEncoder.init().encode(a) // { name: "123" }
let a2 = try! JSONDecoder().decode(S.self, from: jsonA)
assert(a2.name == .some("123"))


let b = S(name: nil)
let jsonB = try! JSONEncoder.init().encode(b) // {}
let b2 = try! JSONDecoder().decode(S.self, from: jsonB)
assert(b2.name == .none)


let c = S(name: .some(nil)) // or .some(.none)
let jsonC = try! JSONEncoder.init().encode(c) // { name: null }
let c2 = try! JSONDecoder().decode(S.self, from: jsonC)
assert(c2.name == .some(.none)) // fails the assertion, because c2.name == .none

The problem is the last line, c2.name is .none and not .some(.none) as expected.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions