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("🛑 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.