Zonily Jame
Zonily Jame

Reputation: 5349

How to make self.dynamicType into a typealias

Basically I want to add a typealias to UIViewController or any other default swift classes. The reasoning behind this is that I want to abstract my code so that I can access some static functions by just using this instead of self.dynamicType

extension UIViewController {
    typealias this = TheClassThatSubclassedThis
}

class DetailViewController: UIViewController {
    func doStuff() {
        this.doStaticStuff()
    }

    static func doStaticStuff() {
        ...
    }
}

I know this is possible by creating a protocol, then just implement said protocol to the class I want to implement it to, like this

protocol CanAccessStaticSelf {
    typealias this
}

class DetailVC: UIViewController, CanAccessStaticSelf {
    typealias this = DetailVC
}

But is there a more efficient way to do this? Like for example, by just subclassing a certain class or by extending a superclass?

Like this for example

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)
    }
}

Upvotes: 1

Views: 519

Answers (2)

Paulo Mattos
Paulo Mattos

Reputation: 19339

Try this instead:

protocol CanAccessStaticSelf {
    typealias this = Self
}

...but what you are trying to achieve looks somewhat confusing to me ;-(


Thanks to this proposal from Erica Sadun we all might be able to use the Self keyword for that in the near future.

For instance:

class MyClass {
    static func staticMethod() { ... }
    func instanceMethod() {
        MyClass.staticMethod()
        Self.staticMethod()
     }
}

Upvotes: 1

jayesh kanzariya
jayesh kanzariya

Reputation: 120

it is not possible to access through this. but you can access through "UIViewController.defaultNibName".

Upvotes: 0

Related Questions