Pass AnyObject as a generic T parameter in Swift 4

I have an interesting problem:

class ListCache {

    public func getCachedList<T: Codable>() -> [T]? {
        //loads list from file cache using Codable
    }

}

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.

+4
source share
2 answers

, . [Foo] Array<Foo>, ( Array<clazz>, ). , clazz, , , , .

AFAIK, :

  • , , Objective-C -style, [Codable] :

  • , : - (

, , , , .

+3

class ListCache {

  public func getCachedList<T: Cachable>() -> [T] {
    return [(Foo() as! T)]
  }

}

protocol Cachable: Codable { }

class CachableClass: Cachable {
  class func test() -> String {
    return "blo"
  }
}

extension Cachable {

  static func cachedValues() -> [Self] {
    return cachedValuesTemplate(type: self)
  }

  private static func cachedValuesTemplate<T: Cachable>(type: T.Type) -> [T] {
    return ListCache().getCachedList()
  }

}

class Foo: CachableClass { }

var listsToLoad: [CachableClass.Type] = [Foo.self]
for clazz in listsToLoad {
  print(clazz.cachedValues().count)
}
0

Source: https://habr.com/ru/post/1695246/


All Articles