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

assertTypeIsEncodable should throw, not preconditionFailure

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Resolved
    • Priority: Medium
    • Resolution: Won't Do
    • Component/s: None
    • Labels:

      Description

      Docs for JSONEncoder.encode() state:

      • The value fails to encode, or contains a nested value that fails to encode—this method throws the corresponding error.

      Yet the actual implementation appears to do something more like

      https://gist.github.com/mishagray/3ee82a3a82f357bfbf8ff3b3d9eca5cd#file-realmswift-codable-swift-L19

      i.e., a preconditionFailure.

      Testing the following in a playground

      let encodable = [NSError(domain: "domain", code: *100*, userInfo: *nil*)]

      try? JSONEncoder().encode(encodable)

      we see that, unlike the promised throw, execution halts with a fatal error.

      This is contrary to desirable function, in that there is no way to determine whether, for example, an Array (which claims conformance with Encodable and therefore can't be skipped via a guard) will successfully encode or simply crash.

      Ideally, this is exactly the purpose of try, which should allow us to get a result or not if none can be had.

        Attachments

          Activity

            People

            • Assignee:
              Unassigned
              Reporter:
              omnius Stephen Goodman
            • Votes:
              0 Vote for this issue
              Watchers:
              3 Start watching this issue

              Dates

              • Created:
                Updated:
                Resolved: