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

Create a reusable file decoder with different Models

I can have multiple models and they could be within an array or not, for example:

[Model1] or Model or [Model2] or [String: [Model2]]

This is my attempt to reuse the same function:

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

/// Decode existing file on disk
func decodeFileStoredInDisk(modelToDecode: Any, fileName: String, fileExtension: String) -> Any? {
    var decodedFile: Any = []
    
    do {
        let fileURL = try FileManager.default
            .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
            .appendingPathComponent(fileName + fileExtension)
        
        let data = try Data(contentsOf: fileURL)
        decodedFile = try JSONDecoder().decode(modelToDecode.self, from: data)
        
    } catch {
        print("🛑 Error decoding file disk: \(error)")
    }
    
    return decodedFile
}

The problem I’m having is that it complains:

Cannot convert value of type 'Any' to expected argument type 'Any.Protocol'

I tried the suggestion:

decodedFile = try JSONDecoder().decode(modelToDecode.self as! Any.Protocol, from: data)

but still complains with:

Protocol 'Any' as a type cannot conform to 'Decodable'

The error is in modelToDecode, if I put the exact model: [Model1] it likes that.

How can I use any type there?

>Solution :

The decoder needs to know the static type therefore Any is not supported at all.

Use a generic type constrained to Decodable like this

func decodeFileStoredInDisk<T : Decodable>(modelToDecode: T.Type, fileName: String, fileExtension: String) throws -> T {
    let fileURL = try FileManager.default
        .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
        .appendingPathComponent(fileName)
        .appendingPathExtension(fileExtension)
        
    let data = try Data(contentsOf: fileURL)
    return try JSONDecoder().decode(T.self, from: data)
}

And the function passes a possible error to the caller.

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