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

Allow JSONEncoder to Encode Top-Level Fragments

    XMLWordPrintable

    Details

      Description

      Codable single values that are not containers currently cannot be converted to json with JSONEncoder.

      That would be helpful though, example use case: Persist a simple enum to UserDefaults.

      Example code:

      enum E: Int, Codable {
      	case one
      }
      
      func saveCodableToUserDefaults<T: Codable>(_ object: T, forKey key: String) {
      	do {
      		// note that we could use either PropertyListEncoder or JSONEncoder, we decided for JSONEncoder - do never change, or old data will not be able to be read again
      		let data = try JSONEncoder().encode(object)
      		UserDefaults.standard.set(data, forKey: key)
      	}
      	catch {
      		assertionFailure()
      	}
      }
      
      saveCodableToUserDefaults(E.one, forKey: "test") // assertionFailure
      

      Also see discussion:
      https://forums.swift.org/t/top-level-t-self-encoded-as-number-json-fragment/11001

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                Unassigned
                Reporter:
                fabb Fabian Ehrentraud
              • Votes:
                1 Vote for this issue
                Watchers:
                5 Start watching this issue

                Dates

                • Created:
                  Updated:
                  Resolved: