繁体   English   中英

通过比较实例属性类型和泛型参数来约束泛型函数

[英]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

您要求的是对类型约束进行某种逻辑OR

... where D == HasFirstDependency || HasSecondDependency

类型约束的分离在 swift 中是不可能的。 引用通常被拒绝的更改

类型约束中的析取(逻辑 OR):这些包括匿名联合类类型(例如(Int | String),用于可以由整数或字符串居住的类型)。 “[这种类型的约束]是类型系统不能也不应该支持的东西。”

一种可能的解决方案是使依赖项符合通用协议。 老实说,这并不能完全解决检测“遗忘”依赖项的问题,因为所有依赖项都必须实现这个通用协议。 此处讨论了这种方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM