Learn Courses My Dashboard

UUID, what’s the difference?

I’m trying to understand more about the UUID, but can’t understand it 100%

In a class/struct when you give your “Model” properties such

Var id: UUID? Or Var id = UUID()
Var name: String
Var age: Int

What’s the difference between the id properties? One is an optional and needs to for fetching data in the JSON parsing. That part I understand. You loop it.

What I haven’t seen an example where you set the property to “var id = UUID().

Is there someone in this community that maybe can explain how it works?

/ Nicholas.

var id: UUID? defines an id property that is an Optional<UUID>. By default it is nil and you can assign it a value.

var id = UUID() defines an id property that is a UUID and is given a value when the struct is created. You don’t need to do anything for it to have an assigned value.

You can use either one when decoding JSON. It just depends on if you want your decoded instance to be automatically assigned an id when it gets created or if you want to manually assign an id yourself afterwards.

And the type of that id will always be an Optional<UUID> with the UUID? method. That means you will always have to remember to unwrap it when you want to use it. Versus the = UUID() method, which gives you a type of UUID that’s not Optional and so never needs unwrapping.

Also, keep in mind that to use the UUID? method, you have to make your id property a var, meaning you run the risk of accidentally changing it if you make a mistake in your code somewhere. With the = UUID() method, the id is assigned at creation and you can make it a let so the value cannot be changed later.

Sample Playground code:

let jsonData = #"{"name": "Charlotte Grote", "occupation": "solver"}"#.data(using: .utf8)!

struct Person: Identifiable, Codable {
    let id = UUID() //let's create a UUID value
    let name: String
    let occupation: String
}

do {
    let decoder = JSONDecoder()
    let person = try decoder.decode(Person.self, from: jsonData)
    print(person.name) //Charlotte Grote
    print(person.id) //B180E929-9699-4B3A-B8A7-A1DF8DB4A3A9
    print(type(of: person.id)) //UUID
} catch {
    print(error)
}

versus this one:

let jsonData = #"{"name": "Charlotte Grote", "occupation": "solver"}"#.data(using: .utf8)!

struct Person: Identifiable, Codable {
    //id must be var so we can change it later
    var id: UUID? //default value is nil
    let name: String
    let occupation: String
}

do {
    let decoder = JSONDecoder()
    //person needs to be a var here as well so that we can change its properties
    var person = try decoder.decode(Person.self, from: jsonData)
    person.id = UUID()
    print(person.name) //Charlotte Grote
    print(person.id) //Optional(D5A1CDD4-7E49-43A4-AEB1-5455F0DEB2D5)
    print(type(of: person.id)) //Optional<UUID>
} catch {
    print(error)
}

It’s your call which method you prefer and want to use.

2 Likes

Very well explained, thank you