我有这样的协议:
protocol Repository {
associatedtype Entity: EntityType
func getAll() throws -> [Entity]
}
和符合Repository的通用类型:
class AnyRepository<Entity:EntityType>: Repository {
public init<ConcreteRepository: Repository>(_ repository: ConcreteRepository) where ConcreteRepository.Entity == Entity {
...
}
}
我希望能够将实体名称映射到各自的存储库,如此
class Saver<Entity: EntityType> {
var repository: AnyRepository<Entity> {
if User.name == Entity.name {
return AnyRepository(UserRepository())
}
}
}
但是我收到错误&#39;无法转换类型&#39; AnyRepository&#39;的返回表达式(又名&#39; AnyRepository&#39;)返回类型&#39;
用户是一个实体类型,就像Saver类的通用参数
一样任何想法,任何帮助将不胜感激?提前致谢
答案 0 :(得分:0)
这不能安全地工作,因为现在当你调用这样的函数时:
Saver<Car>().repository
您返回AnyRepository<Car>
,但实际类型为AnyRepository<User>
,因此,只要您调用某些特定于Car
的方法,它就不会User
。在ConstraintLayout
类中发现并抛出错误,这就是为什么不允许这样做的原因。