【问题标题】:Swift Generic is treated as a parent in typealiasSwift Generic 在 typealias 中被视为父级
【发布时间】:2016-06-03 15:22:02
【问题描述】:

我有一个方法:

public func someMethod<Controller>(controller: Controller) {
    print(controller)

    typealias HandlerType = Controller -> UIViewController
    let handler: HandlerType

    print(handler.dynamicType)
}

在使用 UIViewController 的子实例(在我的例子中是 ViewController)调用它之后,它会打印:

<Test.ViewController: 0x7fc43be479d0>
UIViewController -> UIViewController

我的目标是拥有这样的类型别名:

Test.ViewController -> UIViewController

我有 typealias 和声明的 valriable:

public typealias ControllerType = UIViewController 
public private(set) static var visibleController: ControllerType?

而方法调用是:

if let controller = visibleController { 
    someMethod(controller) 
}

我不明白为什么 ViewController 在 typealias 中变成 UIViewController,所以如果有人遇到此类问题和/或有解决方案,请告诉我。

提前谢谢你。

【问题讨论】:

  • 那是你的完整代码吗?在我看来,这会发生在诸如Controller: UIViewController 之类的通用约束下。
  • 其实这个例子没关系。对于我的代码,就像您说的那样,我只是更改了它以确保即使在这种情况下它也不起作用。
  • 您遇到了类型系统问题。即使您认为这无关紧要,我也会鼓励您准确了解示例中的类型。

标签: swift generics type-alias


【解决方案1】:

这是因为您的controller 的静态和动态类型不同。

静态类型取自您的 ControllerType 类型别名,您已将其定义为 UIViewController。动态类型与visibleController 指向的实例类型相同——在本例中为Test.ViewController

因为泛型是从您传递给函数的静态类型推断出来的(它们的特化发生在编译时),所以Controller 将被推断为UIViewController。因此,您的 typealias 将是 UIViewController -&gt; UIViewController,这就是您的 handler 中的 dynamicType 将返回的内容(未分配时它似乎回退到静态类型)。

另一方面,您的controller 的动态类型确实是Test.ViewController,因为这是您传入的实例的dynamicType

至于解决方案,不知道你在这里想要实现什么,很难说。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-21
    • 1970-01-01
    相关资源
    最近更新 更多