Home > Back-end >  Swift: How to pass a codable type as a function input to encode or decode json
Swift: How to pass a codable type as a function input to encode or decode json

Time:12-20

I would like to make a helper function which takes input of encodable/decodable type in order to encode or decode json. I have tried

static func loadCache<T:Decodable>(fileName:String, type:T)throws->T{
        let data = try FileManager.loadCache(fileName: fileName)
        return try JSONDecoder().decode(T.self, from: data)
    }

Using the function

let products = try loadCache(fileName: Product.cacheFileName(), type: [Product])

I am getting error Type '[Product].Type' cannot conform to 'Decodable'

what is the correct way to pass this to a function Thanks

CodePudding user response:

You're very close. Your syntax is just slightly incorrect. You want to pass the type as a value, not a value of the type, so this is the signature you need:

static func loadCache<T:Decodable>(fileName:String, type: T.Type) throws -> T{
                                                           ^^^^^

Swift requires that you be very explicit about passing types as values. It requires adding .self:

let products = try loadCache(fileName: Product.cacheFileName(),
                             type: [Product].self)
                                            ^^^^^
  • Related