Home > Net >  Create a reusable file decoder with different Models
Create a reusable file decoder with different Models

Time:12-18

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:

/// 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("           
  • Related