I am receiving JSON text, converting it to Data, and then using JSONDecoder to create a concrete type represented by the JSON text/string.
It does work with my "complex" data structure (which implements Codable), or even a simple array of Int as shown below:
import Foundation
let jsonTextContainigArrayOfInt: String = "[1,2,3]"
let data = jsonTextContainigArrayOfInt.data(using: .utf8)!
do {
let arrayOfInt: [Int] = try JSONDecoder().decode([Int].self, from: data)
for n in arrayOfInt {
print(n)
}
}
catch {
print(error)
}
The previous code works and correctly creates the array of Int and prints them.
The problem occurs when doing this same approach with a single Int in the JSON-text:
import Foundation
let jsonTextContainigOneInt: String = "1"
let data = jsonTextContainigOneInt.data(using: .utf8)!
do {
let myInt: Int = try JSONDecoder().decode(Int.self, from: data)
print(myInt)
}
catch {
print(error)
}
For this second approach, I get the following error:
"The operation could not be completed"
*** Edit ***
Bug report for this already exists: https://bugs.swift.org/browse/SR-6163