[英]How To constraint parameter of generic type in function, to sibling parameter
[英]Constraint generic function by comparing instance property type with generic parameter
我想继承 ViewControllers 来创建一个通用的 Coordinator 类。 这个协调器类应该能够安全地将依赖项注入到子协调器类中。 子协调器应该只能访问显式定义的依赖项。 我用抽象类制作了以下工作操场来布局问题。 我对如何解决所描述的问题的其他想法持开放态度。
import Foundation
protocol HasFirstDependency {
var first: Any? { get }
}
protocol HasSecondDependency {
var second: Any? { get }
}
typealias AllDependencies = HasFirstDependency & HasSecondDependency
struct AppDependencies: AllDependencies {
var first: Any?
var second: Any?
}
class Coordinator<D> {
var dependencies: D?
}
extension Coordinator {
static func initialize() -> Coordinator<D> {
return Coordinator<D>()
}
}
class ParentCoordinator: Coordinator<AllDependencies> {
var children: [Any] = []
}
class FirstChildCoordinator: Coordinator<HasFirstDependency> {}
class SecondChildCoordinator: Coordinator<HasSecondDependency> {}
以下代码概述了问题(请参阅注释 1. 和 2.)。 无论如何要避免在编译时以描述的方式强制转换和限制 childType?
extension ParentCoordinator {
func add<C: Coordinator<D>, D>(childType: C.Type) { // 2. ... by setting a constraint like this: "where self.dependecies is D?"
let child = C.initialize()
children.append(child)
if let dependencies: D? = self.dependencies as? D? { // 1. is there any way to avoid this casting ...
child.dependencies = dependencies
} else {
assertionFailure("parentCoordinator does not hold child dependencies")
}
}
}
let parent = ParentCoordinator()
parent.dependencies = AppDependencies(first: "bla", second: "blup")
parent.add(childType: FirstChildCoordinator.self)
let child = parent.children.first as? Coordinator<HasFirstDependency>
print(type(of: parent.dependencies)) // Optional<HasFirstDependency & HasSecondDependency>
print(parent.dependencies?.first) // Optional("bla")
print(parent.dependencies?.second) // Optional("blup")
print(type(of: child?.dependencies)) // Optional<HasFirstDependency>
print(child?.dependencies?.first) // Optional("bla")
//print(child?.dependencies?.second) // does not compile, what I wanted to achieve
更具体地说:以下致命错误是我想在编译时捕获的错误。
protocol ForgottenDependency {
var forgotten: Any? { get }
}
class ThirdChildCoordinator: Coordinator<ForgottenDependency> {}
parent.add(childType: ThirdChildCoordinator.self) // Fatal error: parentCoordinator does not hold child dependencies: file MyPlayground.playground, line 49
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.