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

Decode an encoded double optional fails



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

      Swift 5.0


       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.




            • Assignee:
              bendjones Ben D. Jones
              ChaosCoder Andreas Ganske
            • Votes:
              0 Vote for this issue
              2 Start watching this issue


              • Created: