基本上,我希望在UIViewController或任何其他默认的快速类中添加一个类型。这背后的原因是我想抽象我的代码,这样我就可以只使用this而不是self.dynamicType来访问一些静态函数。
extension UIViewController {
typealias this = TheClassThatSubclassedThis
}
class DetailViewController: UIViewController {
func doStuff() {
this.doStaticStuff()
}
static func doStaticStuff() {
...
}
}我知道这是可能的,通过创建一个protocol,然后将上述协议实现到我想要实现的类,如下所示
protocol CanAccessStaticSelf {
typealias this
}
class DetailVC: UIViewController, CanAccessStaticSelf {
typealias this = DetailVC
}但是否有更有效的方法来做到这一点呢?例如,只对某个类进行子类化,还是扩展超类?
例如,像这样
extension UIViewController {
public static var defaultNibName: String {
return self.description().componentsSeparatedByString(".").dropFirst().joinWithSeparator(".")
}
}
class DetailVC: UIViewController, CanAccessStaticSelf {
func doSomeStuffAgain() {
// no other code just subclass and I can access self.dynamicType as just `this`
print(this.defaultNibName)
}
}发布于 2017-04-21 10:53:51
试一试:
protocol CanAccessStaticSelf {
typealias this = Self
}...but你想要达到的目标在我看来有点令人困惑;
多亏了埃丽卡·萨顿的提议,我们都可以在不久的将来使用Self关键字。
例如:
class MyClass {
static func staticMethod() { ... }
func instanceMethod() {
MyClass.staticMethod()
Self.staticMethod()
}
}发布于 2017-04-21 10:51:43
无法通过此访问。但您可以通过"UIViewController.defaultNibName“访问。
https://stackoverflow.com/questions/43538278
复制相似问题