I have an interesting problem:
class ListCache {
public func getCachedList<T: Codable>() -> [T]? {
}
}
let's say I have a Foo class:
class Foo: Codable {
var bar = ""
}
Now I can do something like this:
let array: [Foo] = ListCache().getCachedList()
but I can not do something like this:
var listsToLoad: [AnyClass] = [Foo.self]
let clazz = listsToLoad[0]
let array: [Codable] = ListCache().getCachedList()
The compiler gives me an error:
Unable to explicitly allocate a generic function
This means that I cannot call getCachedList()in a loop because I must explicitly tell it the type of class.
Is there any way to achieve this? I also tried using generic classes, but I pretty much end up at the same point.
Edit:
I tried to create:
class CodableClass: Codable {
}
then
class Foo: CodableClass {
}
and now the compiler says clazz is not declared:
var listsToLoad: [CodableClass.Type] = [Foo.self]
for clazz in listsToLoad {
if let array: [clazz] = ListCache().getCachedList() {
print(array.count)
}
}
I tried clazz.Typeand clazz.self.
source
share