Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Swift and JSON UUID – Write to var and read from the var the id's are different

I did wrote some code to save some struct to disk in JSON format.
However, if I save it in a variable and keep that and use it to decoded it then the UUID’s are different.

import Foundation
import PlaygroundSupport
import Swift

struct Project: Codable, Identifiable, Hashable  {
    let id: UUID = UUID()
    let id2: String = UUID().uuidString 
    let name: String
}

let project = Project(name: "PP50")
let encodedData = try JSONEncoder().encode(project)
let jsonString = String(data: encodedData,
                        encoding: .utf8)

print(project.id)
print(project.id2)
print(project.name)
print(jsonString)
print("===================")

if let dataFromJsonString = jsonString?.data(using: .utf8) {
    let projectFromData = try JSONDecoder().decode(Project.self, from: dataFromJsonString)
    print(projectFromData)
    print(projectFromData.name)
    print(projectFromData.id) // <<< why is the id and id'2 different
    print(projectFromData.id2)
}

The result is:

826FEC8A-7FE0-4E6C-8DC1-A0DFA4FC75BE
2D15A1B8-B936-4829-8DC2-9C44B261712E
PP50
Optional("{\"id\":\"826FEC8A-7FE0-4E6C-8DC1-A0DFA4FC75BE\",\"id2\":\"2D15A1B8-B936-4829-8DC2-9C44B261712E\",\"name\":\"PP50\"}")
===================
Project(id: E951D459-3C0E-43A3-B9C6-2CCF2EB1AEE3, id2: "3C97B5C3-054D-4372-800D-9210439F48C2", name: "PP50")
PP50
E951D459-3C0E-43A3-B9C6-2CCF2EB1AEE3
3C97B5C3-054D-4372-800D-9210439F48C2

Maybe a simple answer, but I don’t see it yet.
Why is the outcome of the id different then the one created?
How come? How to solve this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

All you need to do is to var declare your id properties and they will be included in the decoding

var id: UUID = UUID()
var id2: String = UUID().uuidString
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading