Logo 61e73bc61c0e1780102320e879dc3cac0e29303ea8894dd8f10c942f3ba8120f

otters.io

An adorable little blog

Universal Self in Swift 3

Saturday — April 30th, 2016

Do you have any static methods on your classes or structs? Normally to call those, you’d have to write:

MySuperFancyExampleClass.staticMethod()

If you were referencing something's type inside an instance method you've had the option of saying self.dynamicType instead of the full class name which can be a bit shorter in certain cases. For example:

extension MySuperFancyExampleClass {
    func someInstanceMethod() {
        self.dynamicType.staticMethod()
    }
}

Universal Self

What is dynamic, besides a terribly overused marketing term? dynamicType grabs the runtime type of whatever is asking for it and returns it as a value you can work with. In plain English, it gives you back the type of a thing.

Coming soon to a Swift near you is the ability to be even lazier! Thanks to a newly accepted proposal by Erica Sadun for a “Universal Self” we'll be able to access these methods using the keyword Self (capital ‘S’).

extension MySuperFancyExampleClass {
    func someInstanceMethod() {
        Self.staticMethod()
    }
}

The usage makes sense; little ‘s’ self for the instance, big ‘S’ Self for the type. This is poised to replace the dynamicType keyword entirely in Swift 3. Another neat time saver that tidies up the language is a win in my book.