4
let encoder = JSONEncoder()

do {
   let encodData = try encoder.encode("test string") // same as Int type
   print(encodData) // nil
} catch let err {
   print(err.localizedDescription) // The data couldn’t be written because it isn’t in the correct format.
}

how to encode these type value

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
HonQii
  • 43
  • 2
  • 4

1 Answers1

5

The top-level (root) JSON object can only be an array or dictionary. For example:

do {
    let encoder = JSONEncoder()
    let encodData = try encoder.encode(["test string"])
    print(String(data: encodData, encoding: .utf8)!) 
    // ["test string"]

} catch {
    print(error.localizedDescription)
}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382