gpt4 book ai didi

swift - Swinject:使用元类型列表进行解析

转载 作者:行者123 更新时间:2023-11-28 06:16:45 26 4
gpt4 key购买 nike

我正在尝试创建一个函数来返回一个元类型数组,然后我可以使用它来解析来自 Swinject Resolver 的实例。这是我的代码:

protocol Task: class { }

func getTypes() -> [Task.Type] {
return [ConcreteTaskA.self, ConcreteTaskB.self]
}

var concreteTasks = [Task]()
for type in getTypes() {
// Use a Swinject Container to resolve the metatype.
let task = container.resolver.resolve(type)! // Error here: Cannot invoke 'resolve' with an argument list of type '(Task.Type)'
concreteTasks.append(task)
}

我不确定如何解决这个问题。我是否需要通过 getTypes() 方法以某种方式使用泛型?解析时是否需要调用一些等效的 type.self

我的要求是我可以定义要由解析器解析的元类型列表 ([ConcreteTaskA.self, ConcreteTaskB.self])。

最佳答案

所以事实证明问题可能出在使用协议(protocol)上。我可以让以下工作......

for type in getTypes() {
// Use a Swinject Container to resolve the metatype.
if let aType = type as? ConcreteTaskA.Type {
let task = container.resolver.resolve(aType)!
concreteTasks.append(task)
}
}

...但显然不需要先检查每种类型会更好。

但是,如果我们将协议(protocol)更改为基类,一切都会按预期进行:

class Task { }
class ConcreteTaskA: Task { }
class ConcreteTaskB: Task { }

func getTypes() -> [Task.Type] {
return [ConcreteTaskA.self, ConcreteTaskB.self]
}

var concreteTasks = [Task]()
for type in getTypes() {
// Use a Swinject Container to resolve the metatype.
let task = container.resolver.resolve(type)!
concreteTasks.append(task)
}

关于swift - Swinject:使用元类型列表进行解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44895006/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com