How to call Type Methods within an instance method

IosClassMethodsTypesSwift

Ios Problem Overview


Apple has a nice explanation of Type (Class) Methods, however, their example looks like this:

class SomeClass {
    class func someTypeMethod() {
        // type method implementation goes here
    }
}
SomeClass.typeMethod()

I see this exact same example parroted everywhere. My problem is, I need to call my Type Method from within an instance of my class, and that doesn't seem to compute.

I MUST be doing something wrong, but I noticed that Apple does not yet support Class Properties. I'm wondering if I'm wasting my time.

I tried this in a playground:

class ClassA
{
    class func staticMethod() -> String { return "STATIC" }

    func dynamicMethod() -> String { return "DYNAMIC" }

    func callBoth() -> ( dynamicRet:String, staticRet:String )
    {
        var dynamicRet:String = self.dynamicMethod()
        var staticRet:String = ""
    
//        staticRet = self.class.staticMethod() // Nope
//        staticRet = class.staticMethod() // No way, Jose
//        staticRet = ClassA.staticMethod(self) // Uh-uh
//        staticRet = ClassA.staticMethod(ClassA()) // Nah
//        staticRet = self.staticMethod() // You is lame
//        staticRet = .staticMethod() // You're kidding, right?
//        staticRet = this.staticMethod() // What, are you making this crap up?
//        staticRet = staticMethod()  // FAIL
    
        return ( dynamicRet:dynamicRet, staticRet:staticRet )
    }
}

let instance:ClassA = ClassA()
let test:( dynamicRet:String, staticRet:String ) = instance.callBoth()

Does anyone have a clue for me?

Ios Solutions


Solution 1 - Ios

var staticRet:String = ClassA.staticMethod()

This works. It doesn't take any parameters so you don't need to pass in any. You can also get ClassA dynamically like this:

Swift 2

var staticRet:String = self.dynamicType.staticMethod()

Swift 3

var staticRet:String = type(of:self).staticMethod()

Solution 2 - Ios

In Swift 3 you can use:

let me = type(of: self)
me.staticMethod()

Solution 3 - Ios

I wanted to add one more twist to this old question.

In today's Swift (I think it switched at 4, but I am not sure), we have replaced type(of: self) with Self (Note the capital "S").

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChris MarshallView Question on Stackoverflow
Solution 1 - IosConnorView Answer on Stackoverflow
Solution 2 - IosDiogo TView Answer on Stackoverflow
Solution 3 - IosChris MarshallView Answer on Stackoverflow