decode JSON UUID correctly

Hello,

 

This is a beginner question but it has me stumped. I have a JSON file in the bundle that includes valid UUIDs generated from within Xcode in the format “D9BB6CD0-FBB9-49B9-9076-07D49E1707B2”. I want to store these in a UUID variable within a struct.

 

struct model: Codable {
    var id: UUID
    var name: String
    …
}

 

I use a standard JSONDecoder() call to import the models.

 

let importedModels = Bundle.main.decode([model].self, from: "models.json")

 

All of the other JSON data imports correctly. In fact it’s been working so well it took me a while to notice that the UUIDs were not being populated. I just get a nil value for variable id.

 

I believe what’s happening is that the decoder isn’t initialising the UUID from the string properly and it’s quietly failing (on UUID data only). But I don’t understand why because in the definition for public struct UUID in Foundation it says,

 

    /// Create a UUID from a string such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F".
    /// 
    /// Returns nil for invalid strings.
    public init?(uuidString string: String)

 

So if the string is valid is should work and I am using valid strings.

 

E621E1F8-C36C-495A-93FC-0C247A3E6E5F     // Foundation documentation
D9BB6CD0-FBB9-49B9-9076-07D49E1707B2     // from models.json

 

Any help greatly appreciated.

Powered by WPeMatico

You may also like...

Comments are closed.