I am using the following struct that conforms to Codable to represent my data within a Set, I then take this set encode it into a JSON Array that looks like the following [{"myexample":"Example5","id":3}]
Struct and Encoding:
struct Model : Codable, Hashable {
var myexample: String?
var id: Int?
}
var mySet: Set<Model> = []
mySet.insert(Model(myexample: "Example4", id: 3))
do {
let json = try JSONEncoder().encode(mySet)
print(String(data: json, encoding: .utf8)!)
} catch {
print(error)
}
How can I inversely decode this array using the following function?
Currently getting this error:
Value of type 'Set' has no member 'utf8'
func processArray(array:Set<Model> = []) {
do{
let mydata = Data(array.utf8.data)
let decoded = try JSONDecoder().decode([Model].self,from: mydata)
print(decoded)
}catch let jsonErr {
print(jsonErr)
}
}
CodePudding user response:
JSON is a string format so a JSON array is also string
func processJSON(_ json: String) {
do{
let mydata = Data(json.utf8)
let decoded = try JSONDecoder().decode(Set<Model>.self,from: mydata)
print(decoded)
} catch {
print(error)
}
}
